blob: f73ec9cb61c5d696b74b412e484b935d14d120f0 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-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 Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-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 Gregore489a7d2010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-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 Gregor3edc4d52010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-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 Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-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 Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000229 OS << "'" << ConversionFunction->getNameAsString() << "'";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor5251f1b2008-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 Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 break;
John McCall0d1da222010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000254 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261}
262
John McCall0d1da222010-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 Gregor5251f1b2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-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 McCalldaa3d6b2009-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 Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000301//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000318 }
John McCall3d988d92009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000323 }
John McCall84d87672009-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 McCall1f82f242009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000338 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339 }
John McCall1f82f242009-11-18 22:49:29 +0000340
John McCalldaa3d6b2009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall1f82f242009-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 Gregor5251f1b2008-10-21 16:13:35 +0000414}
415
Douglas Gregor8e1cf602008-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 Gregor5251f1b2008-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 Gregor2fe98832008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Sebastian Redl42e92c42009-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 Jahanianb3c44f92009-10-01 20:39:51 +0000441/// If @p UserCast, the implicit conversion is being done for a user-specified
442/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000443ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000444Sema::TryImplicitConversion(Expr* From, QualType ToType,
445 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000446 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000447 bool InOverloadResolution,
448 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000450 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000451 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000452 return ICS;
453 }
454
455 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000456 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-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 McCall0d1da222010-01-12 00:44:57 +0000467 ICS.setUserDefined();
Douglas Gregor05379422008-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 Stump11289f42009-09-09 15:08:12 +0000475 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000476 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000477 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000478 = Context.getCanonicalType(From->getType().getUnqualifiedType());
479 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000480 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000481 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000482 // Turn this into a "standard" conversion sequence, so that it
483 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000484 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000485 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000486 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000487 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000488 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000489 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000490 ICS.Standard.Second = ICK_Derived_To_Base;
491 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000492 }
Douglas Gregor576e98c2009-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 McCall6a61b522010-01-13 09:16:55 +0000501 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000502 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000503 }
John McCalle8c8cd22010-01-13 22:30:33 +0000504 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-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 Jahanian21ccf062009-09-23 00:58:07 +0000512 } else {
John McCall65eb8792010-02-25 01:37:24 +0000513 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000514 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000515
516 return ICS;
517}
518
Douglas Gregor40cb9ad2009-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 Gregor26bee0b2008-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 Stump11289f42009-09-09 15:08:12 +0000544bool
545Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000546 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000547 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000548 QualType FromType = From->getType();
549
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000550 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000551 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000552 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000553 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000554 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000555 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000556
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000557 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000558 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000559 if (FromType->isRecordType() || ToType->isRecordType()) {
560 if (getLangOptions().CPlusPlus)
561 return false;
562
Mike Stump11289f42009-09-09 15:08:12 +0000563 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000564 }
565
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000566 // The first conversion can be an lvalue-to-rvalue conversion,
567 // array-to-pointer conversion, or function-to-pointer conversion
568 // (C++ 4p1).
569
Mike Stump11289f42009-09-09 15:08:12 +0000570 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000571 // An lvalue (3.10) of a non-function, non-array type T can be
572 // converted to an rvalue.
573 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000574 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000575 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000576 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000577 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578
579 // If T is a non-class type, the type of the rvalue is the
580 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000581 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
582 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000583 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000584 } else if (FromType->isArrayType()) {
585 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000586 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000587
588 // An lvalue or rvalue of type "array of N T" or "array of unknown
589 // bound of T" can be converted to an rvalue of type "pointer to
590 // T" (C++ 4.2p1).
591 FromType = Context.getArrayDecayedType(FromType);
592
593 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
594 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000595 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000596
597 // For the purpose of ranking in overload resolution
598 // (13.3.3.1.1), this conversion is considered an
599 // array-to-pointer conversion followed by a qualification
600 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Identity;
602 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000603 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000604 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000605 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
607 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000608 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000609
610 // An lvalue of function type T can be converted to an rvalue of
611 // type "pointer to T." The result is a pointer to the
612 // function. (C++ 4.3p1).
613 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000614 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000615 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000616 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000617 SCS.First = ICK_Function_To_Pointer;
618
619 // We were able to resolve the address of the overloaded function,
620 // so we can convert to the type of that function.
621 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000622 if (ToType->isLValueReferenceType())
623 FromType = Context.getLValueReferenceType(FromType);
624 else if (ToType->isRValueReferenceType())
625 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000626 else if (ToType->isMemberPointerType()) {
627 // Resolve address only succeeds if both sides are member pointers,
628 // but it doesn't have to be the same class. See DR 247.
629 // Note that this means that the type of &Derived::fn can be
630 // Ret (Base::*)(Args) if the fn overload actually found is from the
631 // base class, even if it was brought into the derived class via a
632 // using declaration. The standard isn't clear on this issue at all.
633 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
634 FromType = Context.getMemberPointerType(FromType,
635 Context.getTypeDeclType(M->getParent()).getTypePtr());
636 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000637 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000638 } else {
639 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000640 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000641 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000642 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000643
644 // The second conversion can be an integral promotion, floating
645 // point promotion, integral conversion, floating point conversion,
646 // floating-integral conversion, pointer conversion,
647 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000648 // For overloading in C, this can also be a "compatible-type"
649 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000650 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000651 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000652 // The unqualified versions of the types are the same: there's no
653 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000654 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000655 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000656 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000657 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000659 } else if (IsFloatingPointPromotion(FromType, ToType)) {
660 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000662 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000663 } else if (IsComplexPromotion(FromType, ToType)) {
664 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000665 SCS.Second = ICK_Complex_Promotion;
666 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000667 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000668 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000669 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000670 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000672 } else if (FromType->isComplexType() && ToType->isComplexType()) {
673 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000674 SCS.Second = ICK_Complex_Conversion;
675 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000676 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
677 (ToType->isComplexType() && FromType->isArithmeticType())) {
678 // Complex-real conversions (C99 6.3.1.7)
679 SCS.Second = ICK_Complex_Real;
680 FromType = ToType.getUnqualifiedType();
681 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
682 // Floating point conversions (C++ 4.8).
683 SCS.Second = ICK_Floating_Conversion;
684 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000685 } else if ((FromType->isFloatingType() &&
686 ToType->isIntegralType() && (!ToType->isBooleanType() &&
687 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000688 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000689 ToType->isFloatingType())) {
690 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000691 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000693 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
694 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000695 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000696 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000697 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000698 } else if (IsMemberPointerConversion(From, FromType, ToType,
699 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000700 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000701 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000702 } else if (ToType->isBooleanType() &&
703 (FromType->isArithmeticType() ||
704 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000705 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000706 FromType->isBlockPointerType() ||
707 FromType->isMemberPointerType() ||
708 FromType->isNullPtrType())) {
709 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000710 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000711 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000712 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000713 Context.typesAreCompatible(ToType, FromType)) {
714 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000715 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000716 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
717 // Treat a conversion that strips "noreturn" as an identity conversion.
718 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000719 } else {
720 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000721 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000723 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000724
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000725 QualType CanonFrom;
726 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000727 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000728 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000729 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000730 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000731 CanonFrom = Context.getCanonicalType(FromType);
732 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000733 } else {
734 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000735 SCS.Third = ICK_Identity;
736
Mike Stump11289f42009-09-09 15:08:12 +0000737 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000738 // [...] Any difference in top-level cv-qualification is
739 // subsumed by the initialization itself and does not constitute
740 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000741 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000742 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000743 if (CanonFrom.getLocalUnqualifiedType()
744 == CanonTo.getLocalUnqualifiedType() &&
745 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000746 FromType = ToType;
747 CanonFrom = CanonTo;
748 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000749 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000750 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000751
752 // If we have not converted the argument type to the parameter type,
753 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000754 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000755 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000756
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000757 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000758}
759
760/// IsIntegralPromotion - Determines whether the conversion from the
761/// expression From (whose potentially-adjusted type is FromType) to
762/// ToType is an integral promotion (C++ 4.5). If so, returns true and
763/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000764bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000765 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000766 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000767 if (!To) {
768 return false;
769 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000770
771 // An rvalue of type char, signed char, unsigned char, short int, or
772 // unsigned short int can be converted to an rvalue of type int if
773 // int can represent all the values of the source type; otherwise,
774 // the source rvalue can be converted to an rvalue of type unsigned
775 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000776 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
777 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000778 if (// We can promote any signed, promotable integer type to an int
779 (FromType->isSignedIntegerType() ||
780 // We can promote any unsigned integer type whose size is
781 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000782 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000783 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000785 }
786
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787 return To->getKind() == BuiltinType::UInt;
788 }
789
790 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
791 // can be converted to an rvalue of the first of the following types
792 // that can represent all the values of its underlying type: int,
793 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000794
795 // We pre-calculate the promotion type for enum types.
796 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
797 if (ToType->isIntegerType())
798 return Context.hasSameUnqualifiedType(ToType,
799 FromEnumType->getDecl()->getPromotionType());
800
801 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000802 // Determine whether the type we're converting from is signed or
803 // unsigned.
804 bool FromIsSigned;
805 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000806
807 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
808 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000809
810 // The types we'll try to promote to, in the appropriate
811 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000812 QualType PromoteTypes[6] = {
813 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000814 Context.LongTy, Context.UnsignedLongTy ,
815 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000817 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000818 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
819 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000820 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000821 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
822 // We found the type that we can promote to. If this is the
823 // type we wanted, we have a promotion. Otherwise, no
824 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000825 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000826 }
827 }
828 }
829
830 // An rvalue for an integral bit-field (9.6) can be converted to an
831 // rvalue of type int if int can represent all the values of the
832 // bit-field; otherwise, it can be converted to unsigned int if
833 // unsigned int can represent all the values of the bit-field. If
834 // the bit-field is larger yet, no integral promotion applies to
835 // it. If the bit-field has an enumerated type, it is treated as any
836 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000837 // FIXME: We should delay checking of bit-fields until we actually perform the
838 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000839 using llvm::APSInt;
840 if (From)
841 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000842 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000843 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
844 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
845 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
846 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000847
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000848 // Are we promoting to an int from a bitfield that fits in an int?
849 if (BitWidth < ToSize ||
850 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
851 return To->getKind() == BuiltinType::Int;
852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000854 // Are we promoting to an unsigned int from an unsigned bitfield
855 // that fits into an unsigned int?
856 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
857 return To->getKind() == BuiltinType::UInt;
858 }
Mike Stump11289f42009-09-09 15:08:12 +0000859
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000860 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000861 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000862 }
Mike Stump11289f42009-09-09 15:08:12 +0000863
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000864 // An rvalue of type bool can be converted to an rvalue of type int,
865 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000866 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000867 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000868 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869
870 return false;
871}
872
873/// IsFloatingPointPromotion - Determines whether the conversion from
874/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
875/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000876bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000877 /// An rvalue of type float can be converted to an rvalue of type
878 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000879 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
880 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000881 if (FromBuiltin->getKind() == BuiltinType::Float &&
882 ToBuiltin->getKind() == BuiltinType::Double)
883 return true;
884
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000885 // C99 6.3.1.5p1:
886 // When a float is promoted to double or long double, or a
887 // double is promoted to long double [...].
888 if (!getLangOptions().CPlusPlus &&
889 (FromBuiltin->getKind() == BuiltinType::Float ||
890 FromBuiltin->getKind() == BuiltinType::Double) &&
891 (ToBuiltin->getKind() == BuiltinType::LongDouble))
892 return true;
893 }
894
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895 return false;
896}
897
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000898/// \brief Determine if a conversion is a complex promotion.
899///
900/// A complex promotion is defined as a complex -> complex conversion
901/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000902/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000903bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000904 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000905 if (!FromComplex)
906 return false;
907
John McCall9dd450b2009-09-21 23:43:11 +0000908 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000909 if (!ToComplex)
910 return false;
911
912 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000913 ToComplex->getElementType()) ||
914 IsIntegralPromotion(0, FromComplex->getElementType(),
915 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000916}
917
Douglas Gregor237f96c2008-11-26 23:31:11 +0000918/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
919/// the pointer type FromPtr to a pointer to type ToPointee, with the
920/// same type qualifiers as FromPtr has on its pointee type. ToType,
921/// if non-empty, will be a pointer to ToType that may or may not have
922/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000923static QualType
924BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000925 QualType ToPointee, QualType ToType,
926 ASTContext &Context) {
927 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
928 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000929 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000930
931 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000932 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000933 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000934 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000935 return ToType;
936
937 // Build a pointer to ToPointee. It has the right qualifiers
938 // already.
939 return Context.getPointerType(ToPointee);
940 }
941
942 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000943 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000944 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
945 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000946}
947
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000948/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
949/// the FromType, which is an objective-c pointer, to ToType, which may or may
950/// not have the right set of qualifiers.
951static QualType
952BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
953 QualType ToType,
954 ASTContext &Context) {
955 QualType CanonFromType = Context.getCanonicalType(FromType);
956 QualType CanonToType = Context.getCanonicalType(ToType);
957 Qualifiers Quals = CanonFromType.getQualifiers();
958
959 // Exact qualifier match -> return the pointer type we're converting to.
960 if (CanonToType.getLocalQualifiers() == Quals)
961 return ToType;
962
963 // Just build a canonical type that has the right qualifiers.
964 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
965}
966
Mike Stump11289f42009-09-09 15:08:12 +0000967static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000968 bool InOverloadResolution,
969 ASTContext &Context) {
970 // Handle value-dependent integral null pointer constants correctly.
971 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
972 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
973 Expr->getType()->isIntegralType())
974 return !InOverloadResolution;
975
Douglas Gregor56751b52009-09-25 04:25:58 +0000976 return Expr->isNullPointerConstant(Context,
977 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
978 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000979}
Mike Stump11289f42009-09-09 15:08:12 +0000980
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000981/// IsPointerConversion - Determines whether the conversion of the
982/// expression From, which has the (possibly adjusted) type FromType,
983/// can be converted to the type ToType via a pointer conversion (C++
984/// 4.10). If so, returns true and places the converted type (that
985/// might differ from ToType in its cv-qualifiers at some level) into
986/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000987///
Douglas Gregora29dc052008-11-27 01:19:21 +0000988/// This routine also supports conversions to and from block pointers
989/// and conversions with Objective-C's 'id', 'id<protocols...>', and
990/// pointers to interfaces. FIXME: Once we've determined the
991/// appropriate overloading rules for Objective-C, we may want to
992/// split the Objective-C checks into a different routine; however,
993/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000994/// conversions, so for now they live here. IncompatibleObjC will be
995/// set if the conversion is an allowed Objective-C conversion that
996/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000997bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000998 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000999 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001000 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001001 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001002 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1003 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001004
Mike Stump11289f42009-09-09 15:08:12 +00001005 // Conversion from a null pointer constant to any Objective-C pointer type.
1006 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001007 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001008 ConvertedType = ToType;
1009 return true;
1010 }
1011
Douglas Gregor231d1c62008-11-27 00:15:41 +00001012 // Blocks: Block pointers can be converted to void*.
1013 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001014 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001015 ConvertedType = ToType;
1016 return true;
1017 }
1018 // Blocks: A null pointer constant can be converted to a block
1019 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001020 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025
Sebastian Redl576fd422009-05-10 18:38:11 +00001026 // If the left-hand-side is nullptr_t, the right side can be a null
1027 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001028 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
1033
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001034 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001035 if (!ToTypePtr)
1036 return false;
1037
1038 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001039 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001040 ConvertedType = ToType;
1041 return true;
1042 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001043
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001044 // Beyond this point, both types need to be pointers
1045 // , including objective-c pointers.
1046 QualType ToPointeeType = ToTypePtr->getPointeeType();
1047 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1048 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1049 ToType, Context);
1050 return true;
1051
1052 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001053 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001054 if (!FromTypePtr)
1055 return false;
1056
1057 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001058
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059 // An rvalue of type "pointer to cv T," where T is an object type,
1060 // can be converted to an rvalue of type "pointer to cv void" (C++
1061 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001062 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001064 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001065 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001066 return true;
1067 }
1068
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001069 // When we're overloading in C, we allow a special kind of pointer
1070 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001071 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001072 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001074 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001075 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001076 return true;
1077 }
1078
Douglas Gregor5c407d92008-10-23 00:40:37 +00001079 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001080 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001081 // An rvalue of type "pointer to cv D," where D is a class type,
1082 // can be converted to an rvalue of type "pointer to cv B," where
1083 // B is a base class (clause 10) of D. If B is an inaccessible
1084 // (clause 11) or ambiguous (10.2) base class of D, a program that
1085 // necessitates this conversion is ill-formed. The result of the
1086 // conversion is a pointer to the base class sub-object of the
1087 // derived class object. The null pointer value is converted to
1088 // the null pointer value of the destination type.
1089 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001090 // Note that we do not check for ambiguity or inaccessibility
1091 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001092 if (getLangOptions().CPlusPlus &&
1093 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001094 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001095 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001096 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001098 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001099 ToType, Context);
1100 return true;
1101 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001102
Douglas Gregora119f102008-12-19 19:13:09 +00001103 return false;
1104}
1105
1106/// isObjCPointerConversion - Determines whether this is an
1107/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1108/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001109bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001110 QualType& ConvertedType,
1111 bool &IncompatibleObjC) {
1112 if (!getLangOptions().ObjC1)
1113 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001114
Steve Naroff7cae42b2009-07-10 23:34:53 +00001115 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001116 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001117 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001118 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001119
Steve Naroff7cae42b2009-07-10 23:34:53 +00001120 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001121 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001122 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001123 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001124 ConvertedType = ToType;
1125 return true;
1126 }
1127 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001128 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001129 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001130 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001131 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001132 ConvertedType = ToType;
1133 return true;
1134 }
1135 // Objective C++: We're able to convert from a pointer to an
1136 // interface to a pointer to a different interface.
1137 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001138 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1139 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1140 if (getLangOptions().CPlusPlus && LHS && RHS &&
1141 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1142 FromObjCPtr->getPointeeType()))
1143 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001144 ConvertedType = ToType;
1145 return true;
1146 }
1147
1148 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1149 // Okay: this is some kind of implicit downcast of Objective-C
1150 // interfaces, which is permitted. However, we're going to
1151 // complain about it.
1152 IncompatibleObjC = true;
1153 ConvertedType = FromType;
1154 return true;
1155 }
Mike Stump11289f42009-09-09 15:08:12 +00001156 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001157 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001158 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001159 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001160 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001161 else if (const BlockPointerType *ToBlockPtr =
1162 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001163 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001164 // to a block pointer type.
1165 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1166 ConvertedType = ToType;
1167 return true;
1168 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001169 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001170 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001171 else if (FromType->getAs<BlockPointerType>() &&
1172 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1173 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001174 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001175 ConvertedType = ToType;
1176 return true;
1177 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001178 else
Douglas Gregora119f102008-12-19 19:13:09 +00001179 return false;
1180
Douglas Gregor033f56d2008-12-23 00:53:59 +00001181 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001182 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001183 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001184 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001185 FromPointeeType = FromBlockPtr->getPointeeType();
1186 else
Douglas Gregora119f102008-12-19 19:13:09 +00001187 return false;
1188
Douglas Gregora119f102008-12-19 19:13:09 +00001189 // If we have pointers to pointers, recursively check whether this
1190 // is an Objective-C conversion.
1191 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1192 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1193 IncompatibleObjC)) {
1194 // We always complain about this conversion.
1195 IncompatibleObjC = true;
1196 ConvertedType = ToType;
1197 return true;
1198 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001199 // Allow conversion of pointee being objective-c pointer to another one;
1200 // as in I* to id.
1201 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1202 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1203 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1204 IncompatibleObjC)) {
1205 ConvertedType = ToType;
1206 return true;
1207 }
1208
Douglas Gregor033f56d2008-12-23 00:53:59 +00001209 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001210 // differences in the argument and result types are in Objective-C
1211 // pointer conversions. If so, we permit the conversion (but
1212 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001213 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001214 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001215 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001216 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001217 if (FromFunctionType && ToFunctionType) {
1218 // If the function types are exactly the same, this isn't an
1219 // Objective-C pointer conversion.
1220 if (Context.getCanonicalType(FromPointeeType)
1221 == Context.getCanonicalType(ToPointeeType))
1222 return false;
1223
1224 // Perform the quick checks that will tell us whether these
1225 // function types are obviously different.
1226 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1227 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1228 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1229 return false;
1230
1231 bool HasObjCConversion = false;
1232 if (Context.getCanonicalType(FromFunctionType->getResultType())
1233 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1234 // Okay, the types match exactly. Nothing to do.
1235 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1236 ToFunctionType->getResultType(),
1237 ConvertedType, IncompatibleObjC)) {
1238 // Okay, we have an Objective-C pointer conversion.
1239 HasObjCConversion = true;
1240 } else {
1241 // Function types are too different. Abort.
1242 return false;
1243 }
Mike Stump11289f42009-09-09 15:08:12 +00001244
Douglas Gregora119f102008-12-19 19:13:09 +00001245 // Check argument types.
1246 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1247 ArgIdx != NumArgs; ++ArgIdx) {
1248 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1249 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1250 if (Context.getCanonicalType(FromArgType)
1251 == Context.getCanonicalType(ToArgType)) {
1252 // Okay, the types match exactly. Nothing to do.
1253 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1254 ConvertedType, IncompatibleObjC)) {
1255 // Okay, we have an Objective-C pointer conversion.
1256 HasObjCConversion = true;
1257 } else {
1258 // Argument types are too different. Abort.
1259 return false;
1260 }
1261 }
1262
1263 if (HasObjCConversion) {
1264 // We had an Objective-C conversion. Allow this pointer
1265 // conversion, but complain about it.
1266 ConvertedType = ToType;
1267 IncompatibleObjC = true;
1268 return true;
1269 }
1270 }
1271
Sebastian Redl72b597d2009-01-25 19:43:20 +00001272 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001273}
1274
Douglas Gregor39c16d42008-10-24 04:54:22 +00001275/// CheckPointerConversion - Check the pointer conversion from the
1276/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001277/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001278/// conversions for which IsPointerConversion has already returned
1279/// true. It returns true and produces a diagnostic if there was an
1280/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001281bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001282 CastExpr::CastKind &Kind,
1283 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001284 QualType FromType = From->getType();
1285
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001286 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1287 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001288 QualType FromPointeeType = FromPtrType->getPointeeType(),
1289 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001290
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001291 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1292 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001293 // We must have a derived-to-base conversion. Check an
1294 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001295 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1296 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001297 From->getSourceRange(),
1298 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001299 return true;
1300
1301 // The conversion was successful.
1302 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001303 }
1304 }
Mike Stump11289f42009-09-09 15:08:12 +00001305 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001306 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001307 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001308 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001309 // Objective-C++ conversions are always okay.
1310 // FIXME: We should have a different class of conversions for the
1311 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001312 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001313 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001314
Steve Naroff7cae42b2009-07-10 23:34:53 +00001315 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001316 return false;
1317}
1318
Sebastian Redl72b597d2009-01-25 19:43:20 +00001319/// IsMemberPointerConversion - Determines whether the conversion of the
1320/// expression From, which has the (possibly adjusted) type FromType, can be
1321/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1322/// If so, returns true and places the converted type (that might differ from
1323/// ToType in its cv-qualifiers at some level) into ConvertedType.
1324bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001325 QualType ToType,
1326 bool InOverloadResolution,
1327 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001328 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001329 if (!ToTypePtr)
1330 return false;
1331
1332 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001333 if (From->isNullPointerConstant(Context,
1334 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1335 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001336 ConvertedType = ToType;
1337 return true;
1338 }
1339
1340 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001341 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001342 if (!FromTypePtr)
1343 return false;
1344
1345 // A pointer to member of B can be converted to a pointer to member of D,
1346 // where D is derived from B (C++ 4.11p2).
1347 QualType FromClass(FromTypePtr->getClass(), 0);
1348 QualType ToClass(ToTypePtr->getClass(), 0);
1349 // FIXME: What happens when these are dependent? Is this function even called?
1350
1351 if (IsDerivedFrom(ToClass, FromClass)) {
1352 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1353 ToClass.getTypePtr());
1354 return true;
1355 }
1356
1357 return false;
1358}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001359
Sebastian Redl72b597d2009-01-25 19:43:20 +00001360/// CheckMemberPointerConversion - Check the member pointer conversion from the
1361/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001362/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001363/// for which IsMemberPointerConversion has already returned true. It returns
1364/// true and produces a diagnostic if there was an error, or returns false
1365/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001366bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001367 CastExpr::CastKind &Kind,
1368 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001369 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001370 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001371 if (!FromPtrType) {
1372 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001373 assert(From->isNullPointerConstant(Context,
1374 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001375 "Expr must be null pointer constant!");
1376 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001377 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001378 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001379
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001380 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001381 assert(ToPtrType && "No member pointer cast has a target type "
1382 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001383
Sebastian Redled8f2002009-01-28 18:33:18 +00001384 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1385 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001386
Sebastian Redled8f2002009-01-28 18:33:18 +00001387 // FIXME: What about dependent types?
1388 assert(FromClass->isRecordType() && "Pointer into non-class.");
1389 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001390
John McCall5b0829a2010-02-10 09:31:12 +00001391 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001392 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001393 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1394 assert(DerivationOkay &&
1395 "Should not have been called if derivation isn't OK.");
1396 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001397
Sebastian Redled8f2002009-01-28 18:33:18 +00001398 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1399 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001400 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1401 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1402 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1403 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001404 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001405
Douglas Gregor89ee6822009-02-28 01:32:25 +00001406 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001407 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1408 << FromClass << ToClass << QualType(VBase, 0)
1409 << From->getSourceRange();
1410 return true;
1411 }
1412
John McCall5b0829a2010-02-10 09:31:12 +00001413 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001414 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1415 Paths.front(),
1416 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001417
Anders Carlssond7923c62009-08-22 23:33:40 +00001418 // Must be a base to derived member conversion.
1419 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001420 return false;
1421}
1422
Douglas Gregor9a657932008-10-21 23:43:52 +00001423/// IsQualificationConversion - Determines whether the conversion from
1424/// an rvalue of type FromType to ToType is a qualification conversion
1425/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001426bool
1427Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001428 FromType = Context.getCanonicalType(FromType);
1429 ToType = Context.getCanonicalType(ToType);
1430
1431 // If FromType and ToType are the same type, this is not a
1432 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001433 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001434 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001435
Douglas Gregor9a657932008-10-21 23:43:52 +00001436 // (C++ 4.4p4):
1437 // A conversion can add cv-qualifiers at levels other than the first
1438 // in multi-level pointers, subject to the following rules: [...]
1439 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001440 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001441 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001442 // Within each iteration of the loop, we check the qualifiers to
1443 // determine if this still looks like a qualification
1444 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001445 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001446 // until there are no more pointers or pointers-to-members left to
1447 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001448 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001449
1450 // -- for every j > 0, if const is in cv 1,j then const is in cv
1451 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001452 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001453 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001454
Douglas Gregor9a657932008-10-21 23:43:52 +00001455 // -- if the cv 1,j and cv 2,j are different, then const is in
1456 // every cv for 0 < k < j.
1457 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001458 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001459 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Douglas Gregor9a657932008-10-21 23:43:52 +00001461 // Keep track of whether all prior cv-qualifiers in the "to" type
1462 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001463 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001464 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001465 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001466
1467 // We are left with FromType and ToType being the pointee types
1468 // after unwrapping the original FromType and ToType the same number
1469 // of types. If we unwrapped any pointers, and if FromType and
1470 // ToType have the same unqualified type (since we checked
1471 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001472 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001473}
1474
Douglas Gregor576e98c2009-01-30 23:27:23 +00001475/// Determines whether there is a user-defined conversion sequence
1476/// (C++ [over.ics.user]) that converts expression From to the type
1477/// ToType. If such a conversion exists, User will contain the
1478/// user-defined conversion sequence that performs such a conversion
1479/// and this routine will return true. Otherwise, this routine returns
1480/// false and User is unspecified.
1481///
1482/// \param AllowConversionFunctions true if the conversion should
1483/// consider conversion functions at all. If false, only constructors
1484/// will be considered.
1485///
1486/// \param AllowExplicit true if the conversion should consider C++0x
1487/// "explicit" conversion functions as well as non-explicit conversion
1488/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001489///
1490/// \param ForceRValue true if the expression should be treated as an rvalue
1491/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001492/// \param UserCast true if looking for user defined conversion for a static
1493/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001494OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1495 UserDefinedConversionSequence& User,
1496 OverloadCandidateSet& CandidateSet,
1497 bool AllowConversionFunctions,
1498 bool AllowExplicit,
1499 bool ForceRValue,
1500 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001501 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001502 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1503 // We're not going to find any constructors.
1504 } else if (CXXRecordDecl *ToRecordDecl
1505 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001506 // C++ [over.match.ctor]p1:
1507 // When objects of class type are direct-initialized (8.5), or
1508 // copy-initialized from an expression of the same or a
1509 // derived class type (8.5), overload resolution selects the
1510 // constructor. [...] For copy-initialization, the candidate
1511 // functions are all the converting constructors (12.3.1) of
1512 // that class. The argument list is the expression-list within
1513 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001514 bool SuppressUserConversions = !UserCast;
1515 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1516 IsDerivedFrom(From->getType(), ToType)) {
1517 SuppressUserConversions = false;
1518 AllowConversionFunctions = false;
1519 }
1520
Mike Stump11289f42009-09-09 15:08:12 +00001521 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001522 = Context.DeclarationNames.getCXXConstructorName(
1523 Context.getCanonicalType(ToType).getUnqualifiedType());
1524 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001525 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001526 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001527 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001528 // Find the constructor (which may be a template).
1529 CXXConstructorDecl *Constructor = 0;
1530 FunctionTemplateDecl *ConstructorTmpl
1531 = dyn_cast<FunctionTemplateDecl>(*Con);
1532 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001533 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001534 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1535 else
1536 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001537
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001538 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001539 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001540 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00001541 AddTemplateOverloadCandidate(ConstructorTmpl,
1542 ConstructorTmpl->getAccess(),
1543 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001544 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001545 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001546 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001547 // Allow one user-defined conversion when user specifies a
1548 // From->ToType conversion via an static cast (c-style, etc).
John McCallb89836b2010-01-26 01:37:31 +00001549 AddOverloadCandidate(Constructor, Constructor->getAccess(),
1550 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001551 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001552 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001553 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001554 }
1555 }
1556
Douglas Gregor576e98c2009-01-30 23:27:23 +00001557 if (!AllowConversionFunctions) {
1558 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001559 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1560 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001561 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001562 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001563 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001564 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001565 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001566 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1567 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001568 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001569 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001570 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001571 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001572 NamedDecl *D = *I;
1573 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1574 if (isa<UsingShadowDecl>(D))
1575 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1576
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001577 CXXConversionDecl *Conv;
1578 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001579 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001580 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1581 else
John McCalld14a8642009-11-21 08:51:07 +00001582 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001583
1584 if (AllowExplicit || !Conv->isExplicit()) {
1585 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00001586 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
1587 ActingContext, From, ToType,
1588 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001589 else
John McCallb89836b2010-01-26 01:37:31 +00001590 AddConversionCandidate(Conv, I.getAccess(), ActingContext,
1591 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001592 }
1593 }
1594 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001595 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001596
1597 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001598 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001599 case OR_Success:
1600 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001601 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001602 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1603 // C++ [over.ics.user]p1:
1604 // If the user-defined conversion is specified by a
1605 // constructor (12.3.1), the initial standard conversion
1606 // sequence converts the source type to the type required by
1607 // the argument of the constructor.
1608 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001609 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001610 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001611 User.EllipsisConversion = true;
1612 else {
1613 User.Before = Best->Conversions[0].Standard;
1614 User.EllipsisConversion = false;
1615 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001616 User.ConversionFunction = Constructor;
1617 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001618 User.After.setFromType(
1619 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001620 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001621 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001622 } else if (CXXConversionDecl *Conversion
1623 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1624 // C++ [over.ics.user]p1:
1625 //
1626 // [...] If the user-defined conversion is specified by a
1627 // conversion function (12.3.2), the initial standard
1628 // conversion sequence converts the source type to the
1629 // implicit object parameter of the conversion function.
1630 User.Before = Best->Conversions[0].Standard;
1631 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001632 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001633
1634 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001635 // The second standard conversion sequence converts the
1636 // result of the user-defined conversion to the target type
1637 // for the sequence. Since an implicit conversion sequence
1638 // is an initialization, the special rules for
1639 // initialization by user-defined conversion apply when
1640 // selecting the best user-defined conversion for a
1641 // user-defined conversion sequence (see 13.3.3 and
1642 // 13.3.3.1).
1643 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001644 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001646 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001647 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001648 }
Mike Stump11289f42009-09-09 15:08:12 +00001649
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001650 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001651 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001652 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001653 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001654 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001655
1656 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001657 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001658 }
1659
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001660 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001661}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001662
1663bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001664Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001665 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001666 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001667 OverloadingResult OvResult =
1668 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1669 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001670 if (OvResult == OR_Ambiguous)
1671 Diag(From->getSourceRange().getBegin(),
1672 diag::err_typecheck_ambiguous_condition)
1673 << From->getType() << ToType << From->getSourceRange();
1674 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1675 Diag(From->getSourceRange().getBegin(),
1676 diag::err_typecheck_nonviable_condition)
1677 << From->getType() << ToType << From->getSourceRange();
1678 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001679 return false;
John McCallad907772010-01-12 07:18:19 +00001680 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001681 return true;
1682}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001683
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001684/// CompareImplicitConversionSequences - Compare two implicit
1685/// conversion sequences to determine whether one is better than the
1686/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001687ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001688Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1689 const ImplicitConversionSequence& ICS2)
1690{
1691 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1692 // conversion sequences (as defined in 13.3.3.1)
1693 // -- a standard conversion sequence (13.3.3.1.1) is a better
1694 // conversion sequence than a user-defined conversion sequence or
1695 // an ellipsis conversion sequence, and
1696 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1697 // conversion sequence than an ellipsis conversion sequence
1698 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001699 //
John McCall0d1da222010-01-12 00:44:57 +00001700 // C++0x [over.best.ics]p10:
1701 // For the purpose of ranking implicit conversion sequences as
1702 // described in 13.3.3.2, the ambiguous conversion sequence is
1703 // treated as a user-defined sequence that is indistinguishable
1704 // from any other user-defined conversion sequence.
1705 if (ICS1.getKind() < ICS2.getKind()) {
1706 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1707 return ImplicitConversionSequence::Better;
1708 } else if (ICS2.getKind() < ICS1.getKind()) {
1709 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1710 return ImplicitConversionSequence::Worse;
1711 }
1712
1713 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1714 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715
1716 // Two implicit conversion sequences of the same form are
1717 // indistinguishable conversion sequences unless one of the
1718 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001719 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001720 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001721 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001722 // User-defined conversion sequence U1 is a better conversion
1723 // sequence than another user-defined conversion sequence U2 if
1724 // they contain the same user-defined conversion function or
1725 // constructor and if the second standard conversion sequence of
1726 // U1 is better than the second standard conversion sequence of
1727 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001728 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001729 ICS2.UserDefined.ConversionFunction)
1730 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1731 ICS2.UserDefined.After);
1732 }
1733
1734 return ImplicitConversionSequence::Indistinguishable;
1735}
1736
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001737// Per 13.3.3.2p3, compare the given standard conversion sequences to
1738// determine if one is a proper subset of the other.
1739static ImplicitConversionSequence::CompareKind
1740compareStandardConversionSubsets(ASTContext &Context,
1741 const StandardConversionSequence& SCS1,
1742 const StandardConversionSequence& SCS2) {
1743 ImplicitConversionSequence::CompareKind Result
1744 = ImplicitConversionSequence::Indistinguishable;
1745
1746 if (SCS1.Second != SCS2.Second) {
1747 if (SCS1.Second == ICK_Identity)
1748 Result = ImplicitConversionSequence::Better;
1749 else if (SCS2.Second == ICK_Identity)
1750 Result = ImplicitConversionSequence::Worse;
1751 else
1752 return ImplicitConversionSequence::Indistinguishable;
1753 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1754 return ImplicitConversionSequence::Indistinguishable;
1755
1756 if (SCS1.Third == SCS2.Third) {
1757 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1758 : ImplicitConversionSequence::Indistinguishable;
1759 }
1760
1761 if (SCS1.Third == ICK_Identity)
1762 return Result == ImplicitConversionSequence::Worse
1763 ? ImplicitConversionSequence::Indistinguishable
1764 : ImplicitConversionSequence::Better;
1765
1766 if (SCS2.Third == ICK_Identity)
1767 return Result == ImplicitConversionSequence::Better
1768 ? ImplicitConversionSequence::Indistinguishable
1769 : ImplicitConversionSequence::Worse;
1770
1771 return ImplicitConversionSequence::Indistinguishable;
1772}
1773
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001774/// CompareStandardConversionSequences - Compare two standard
1775/// conversion sequences to determine whether one is better than the
1776/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001777ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001778Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1779 const StandardConversionSequence& SCS2)
1780{
1781 // Standard conversion sequence S1 is a better conversion sequence
1782 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1783
1784 // -- S1 is a proper subsequence of S2 (comparing the conversion
1785 // sequences in the canonical form defined by 13.3.3.1.1,
1786 // excluding any Lvalue Transformation; the identity conversion
1787 // sequence is considered to be a subsequence of any
1788 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001789 if (ImplicitConversionSequence::CompareKind CK
1790 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1791 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001792
1793 // -- the rank of S1 is better than the rank of S2 (by the rules
1794 // defined below), or, if not that,
1795 ImplicitConversionRank Rank1 = SCS1.getRank();
1796 ImplicitConversionRank Rank2 = SCS2.getRank();
1797 if (Rank1 < Rank2)
1798 return ImplicitConversionSequence::Better;
1799 else if (Rank2 < Rank1)
1800 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001801
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001802 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1803 // are indistinguishable unless one of the following rules
1804 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001805
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001806 // A conversion that is not a conversion of a pointer, or
1807 // pointer to member, to bool is better than another conversion
1808 // that is such a conversion.
1809 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1810 return SCS2.isPointerConversionToBool()
1811 ? ImplicitConversionSequence::Better
1812 : ImplicitConversionSequence::Worse;
1813
Douglas Gregor5c407d92008-10-23 00:40:37 +00001814 // C++ [over.ics.rank]p4b2:
1815 //
1816 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001817 // conversion of B* to A* is better than conversion of B* to
1818 // void*, and conversion of A* to void* is better than conversion
1819 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001820 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001821 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001822 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001823 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001824 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1825 // Exactly one of the conversion sequences is a conversion to
1826 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001827 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1828 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001829 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1830 // Neither conversion sequence converts to a void pointer; compare
1831 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001832 if (ImplicitConversionSequence::CompareKind DerivedCK
1833 = CompareDerivedToBaseConversions(SCS1, SCS2))
1834 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001835 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1836 // Both conversion sequences are conversions to void
1837 // pointers. Compare the source types to determine if there's an
1838 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001839 QualType FromType1 = SCS1.getFromType();
1840 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001841
1842 // Adjust the types we're converting from via the array-to-pointer
1843 // conversion, if we need to.
1844 if (SCS1.First == ICK_Array_To_Pointer)
1845 FromType1 = Context.getArrayDecayedType(FromType1);
1846 if (SCS2.First == ICK_Array_To_Pointer)
1847 FromType2 = Context.getArrayDecayedType(FromType2);
1848
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001849 QualType FromPointee1
1850 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1851 QualType FromPointee2
1852 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001853
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001854 if (IsDerivedFrom(FromPointee2, FromPointee1))
1855 return ImplicitConversionSequence::Better;
1856 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1857 return ImplicitConversionSequence::Worse;
1858
1859 // Objective-C++: If one interface is more specific than the
1860 // other, it is the better one.
1861 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1862 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1863 if (FromIface1 && FromIface1) {
1864 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1865 return ImplicitConversionSequence::Better;
1866 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1867 return ImplicitConversionSequence::Worse;
1868 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001869 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001870
1871 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1872 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001873 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001874 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001875 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001876
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001877 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001878 // C++0x [over.ics.rank]p3b4:
1879 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1880 // implicit object parameter of a non-static member function declared
1881 // without a ref-qualifier, and S1 binds an rvalue reference to an
1882 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001883 // FIXME: We don't know if we're dealing with the implicit object parameter,
1884 // or if the member function in this case has a ref qualifier.
1885 // (Of course, we don't have ref qualifiers yet.)
1886 if (SCS1.RRefBinding != SCS2.RRefBinding)
1887 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1888 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001889
1890 // C++ [over.ics.rank]p3b4:
1891 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1892 // which the references refer are the same type except for
1893 // top-level cv-qualifiers, and the type to which the reference
1894 // initialized by S2 refers is more cv-qualified than the type
1895 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001896 QualType T1 = SCS1.getToType(2);
1897 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001898 T1 = Context.getCanonicalType(T1);
1899 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001900 Qualifiers T1Quals, T2Quals;
1901 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1902 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1903 if (UnqualT1 == UnqualT2) {
1904 // If the type is an array type, promote the element qualifiers to the type
1905 // for comparison.
1906 if (isa<ArrayType>(T1) && T1Quals)
1907 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1908 if (isa<ArrayType>(T2) && T2Quals)
1909 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001910 if (T2.isMoreQualifiedThan(T1))
1911 return ImplicitConversionSequence::Better;
1912 else if (T1.isMoreQualifiedThan(T2))
1913 return ImplicitConversionSequence::Worse;
1914 }
1915 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001916
1917 return ImplicitConversionSequence::Indistinguishable;
1918}
1919
1920/// CompareQualificationConversions - Compares two standard conversion
1921/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001922/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1923ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001924Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001925 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001926 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001927 // -- S1 and S2 differ only in their qualification conversion and
1928 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1929 // cv-qualification signature of type T1 is a proper subset of
1930 // the cv-qualification signature of type T2, and S1 is not the
1931 // deprecated string literal array-to-pointer conversion (4.2).
1932 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1933 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1934 return ImplicitConversionSequence::Indistinguishable;
1935
1936 // FIXME: the example in the standard doesn't use a qualification
1937 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001938 QualType T1 = SCS1.getToType(2);
1939 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001940 T1 = Context.getCanonicalType(T1);
1941 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001942 Qualifiers T1Quals, T2Quals;
1943 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1944 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001945
1946 // If the types are the same, we won't learn anything by unwrapped
1947 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001948 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001949 return ImplicitConversionSequence::Indistinguishable;
1950
Chandler Carruth607f38e2009-12-29 07:16:59 +00001951 // If the type is an array type, promote the element qualifiers to the type
1952 // for comparison.
1953 if (isa<ArrayType>(T1) && T1Quals)
1954 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1955 if (isa<ArrayType>(T2) && T2Quals)
1956 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1957
Mike Stump11289f42009-09-09 15:08:12 +00001958 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001959 = ImplicitConversionSequence::Indistinguishable;
1960 while (UnwrapSimilarPointerTypes(T1, T2)) {
1961 // Within each iteration of the loop, we check the qualifiers to
1962 // determine if this still looks like a qualification
1963 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001964 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001965 // until there are no more pointers or pointers-to-members left
1966 // to unwrap. This essentially mimics what
1967 // IsQualificationConversion does, but here we're checking for a
1968 // strict subset of qualifiers.
1969 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1970 // The qualifiers are the same, so this doesn't tell us anything
1971 // about how the sequences rank.
1972 ;
1973 else if (T2.isMoreQualifiedThan(T1)) {
1974 // T1 has fewer qualifiers, so it could be the better sequence.
1975 if (Result == ImplicitConversionSequence::Worse)
1976 // Neither has qualifiers that are a subset of the other's
1977 // qualifiers.
1978 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001979
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001980 Result = ImplicitConversionSequence::Better;
1981 } else if (T1.isMoreQualifiedThan(T2)) {
1982 // T2 has fewer qualifiers, so it could be the better sequence.
1983 if (Result == ImplicitConversionSequence::Better)
1984 // Neither has qualifiers that are a subset of the other's
1985 // qualifiers.
1986 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001987
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001988 Result = ImplicitConversionSequence::Worse;
1989 } else {
1990 // Qualifiers are disjoint.
1991 return ImplicitConversionSequence::Indistinguishable;
1992 }
1993
1994 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001995 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001996 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001997 }
1998
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001999 // Check that the winning standard conversion sequence isn't using
2000 // the deprecated string literal array to pointer conversion.
2001 switch (Result) {
2002 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002003 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002004 Result = ImplicitConversionSequence::Indistinguishable;
2005 break;
2006
2007 case ImplicitConversionSequence::Indistinguishable:
2008 break;
2009
2010 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002011 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002012 Result = ImplicitConversionSequence::Indistinguishable;
2013 break;
2014 }
2015
2016 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002017}
2018
Douglas Gregor5c407d92008-10-23 00:40:37 +00002019/// CompareDerivedToBaseConversions - Compares two standard conversion
2020/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002021/// various kinds of derived-to-base conversions (C++
2022/// [over.ics.rank]p4b3). As part of these checks, we also look at
2023/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002024ImplicitConversionSequence::CompareKind
2025Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2026 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002027 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002028 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002029 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002030 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002031
2032 // Adjust the types we're converting from via the array-to-pointer
2033 // conversion, if we need to.
2034 if (SCS1.First == ICK_Array_To_Pointer)
2035 FromType1 = Context.getArrayDecayedType(FromType1);
2036 if (SCS2.First == ICK_Array_To_Pointer)
2037 FromType2 = Context.getArrayDecayedType(FromType2);
2038
2039 // Canonicalize all of the types.
2040 FromType1 = Context.getCanonicalType(FromType1);
2041 ToType1 = Context.getCanonicalType(ToType1);
2042 FromType2 = Context.getCanonicalType(FromType2);
2043 ToType2 = Context.getCanonicalType(ToType2);
2044
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002045 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002046 //
2047 // If class B is derived directly or indirectly from class A and
2048 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002049 //
2050 // For Objective-C, we let A, B, and C also be Objective-C
2051 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002052
2053 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002054 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002055 SCS2.Second == ICK_Pointer_Conversion &&
2056 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2057 FromType1->isPointerType() && FromType2->isPointerType() &&
2058 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002059 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002060 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002061 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002062 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002063 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002064 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002065 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002066 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002067
John McCall9dd450b2009-09-21 23:43:11 +00002068 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2069 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2070 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2071 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002072
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002073 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002074 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2075 if (IsDerivedFrom(ToPointee1, ToPointee2))
2076 return ImplicitConversionSequence::Better;
2077 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2078 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002079
2080 if (ToIface1 && ToIface2) {
2081 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2082 return ImplicitConversionSequence::Better;
2083 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2084 return ImplicitConversionSequence::Worse;
2085 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002086 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002087
2088 // -- conversion of B* to A* is better than conversion of C* to A*,
2089 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2090 if (IsDerivedFrom(FromPointee2, FromPointee1))
2091 return ImplicitConversionSequence::Better;
2092 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2093 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002094
Douglas Gregor237f96c2008-11-26 23:31:11 +00002095 if (FromIface1 && FromIface2) {
2096 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2097 return ImplicitConversionSequence::Better;
2098 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2099 return ImplicitConversionSequence::Worse;
2100 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002101 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002102 }
2103
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002104 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002105 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2106 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2107 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2108 const MemberPointerType * FromMemPointer1 =
2109 FromType1->getAs<MemberPointerType>();
2110 const MemberPointerType * ToMemPointer1 =
2111 ToType1->getAs<MemberPointerType>();
2112 const MemberPointerType * FromMemPointer2 =
2113 FromType2->getAs<MemberPointerType>();
2114 const MemberPointerType * ToMemPointer2 =
2115 ToType2->getAs<MemberPointerType>();
2116 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2117 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2118 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2119 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2120 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2121 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2122 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2123 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002124 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002125 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2126 if (IsDerivedFrom(ToPointee1, ToPointee2))
2127 return ImplicitConversionSequence::Worse;
2128 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2129 return ImplicitConversionSequence::Better;
2130 }
2131 // conversion of B::* to C::* is better than conversion of A::* to C::*
2132 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2133 if (IsDerivedFrom(FromPointee1, FromPointee2))
2134 return ImplicitConversionSequence::Better;
2135 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2136 return ImplicitConversionSequence::Worse;
2137 }
2138 }
2139
Douglas Gregor83af86a2010-02-25 19:01:05 +00002140 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2141 (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
Douglas Gregor2fe98832008-11-03 19:09:14 +00002142 SCS1.Second == ICK_Derived_To_Base) {
2143 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002144 // -- binding of an expression of type C to a reference of type
2145 // B& is better than binding an expression of type C to a
2146 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002147 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2148 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002149 if (IsDerivedFrom(ToType1, ToType2))
2150 return ImplicitConversionSequence::Better;
2151 else if (IsDerivedFrom(ToType2, ToType1))
2152 return ImplicitConversionSequence::Worse;
2153 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002154
Douglas Gregor2fe98832008-11-03 19:09:14 +00002155 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002156 // -- binding of an expression of type B to a reference of type
2157 // A& is better than binding an expression of type C to a
2158 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002159 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2160 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002161 if (IsDerivedFrom(FromType2, FromType1))
2162 return ImplicitConversionSequence::Better;
2163 else if (IsDerivedFrom(FromType1, FromType2))
2164 return ImplicitConversionSequence::Worse;
2165 }
2166 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002167
Douglas Gregor5c407d92008-10-23 00:40:37 +00002168 return ImplicitConversionSequence::Indistinguishable;
2169}
2170
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002171/// TryCopyInitialization - Try to copy-initialize a value of type
2172/// ToType from the expression From. Return the implicit conversion
2173/// sequence required to pass this argument, which may be a bad
2174/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002175/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002176/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2177/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002178ImplicitConversionSequence
2179Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002180 bool SuppressUserConversions, bool ForceRValue,
2181 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002182 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002183 ImplicitConversionSequence ICS;
John McCall65eb8792010-02-25 01:37:24 +00002184 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002185 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002186 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002187 SuppressUserConversions,
2188 /*AllowExplicit=*/false,
2189 ForceRValue,
2190 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002191 return ICS;
2192 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002193 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002194 SuppressUserConversions,
2195 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002196 ForceRValue,
2197 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002198 }
2199}
2200
Sebastian Redl42e92c42009-04-12 17:16:29 +00002201/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2202/// the expression @p From. Returns true (and emits a diagnostic) if there was
2203/// an error, returns false if the initialization succeeded. Elidable should
2204/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2205/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002206bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002207 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002208 if (!getLangOptions().CPlusPlus) {
2209 // In C, argument passing is the same as performing an assignment.
2210 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002211
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002212 AssignConvertType ConvTy =
2213 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002214 if (ConvTy != Compatible &&
2215 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2216 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002217
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002218 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002219 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002220 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002221
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002222 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002223 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002224 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002225 /*SuppressUserConversions=*/false,
2226 /*AllowExplicit=*/false,
2227 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002228
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002229 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002230 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002231 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002232 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002233 return Diag(From->getSourceRange().getBegin(),
2234 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002235 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002236 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002237}
2238
Douglas Gregor436424c2008-11-18 23:14:02 +00002239/// TryObjectArgumentInitialization - Try to initialize the object
2240/// parameter of the given member function (@c Method) from the
2241/// expression @p From.
2242ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002243Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002244 CXXMethodDecl *Method,
2245 CXXRecordDecl *ActingContext) {
2246 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002247 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2248 // const volatile object.
2249 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2250 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2251 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002252
2253 // Set up the conversion sequence as a "bad" conversion, to allow us
2254 // to exit early.
2255 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002256
2257 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002258 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002259 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002260 FromType = PT->getPointeeType();
2261
2262 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002263
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002264 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002265 // where X is the class of which the function is a member
2266 // (C++ [over.match.funcs]p4). However, when finding an implicit
2267 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002268 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002269 // (C++ [over.match.funcs]p5). We perform a simplified version of
2270 // reference binding here, that allows class rvalues to bind to
2271 // non-constant references.
2272
2273 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2274 // with the implicit object parameter (C++ [over.match.funcs]p5).
2275 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002276 if (ImplicitParamType.getCVRQualifiers()
2277 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002278 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002279 ICS.setBad(BadConversionSequence::bad_qualifiers,
2280 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002281 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002282 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002283
2284 // Check that we have either the same type or a derived type. It
2285 // affects the conversion rank.
2286 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002287 ImplicitConversionKind SecondKind;
2288 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2289 SecondKind = ICK_Identity;
2290 } else if (IsDerivedFrom(FromType, ClassType))
2291 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002292 else {
John McCall65eb8792010-02-25 01:37:24 +00002293 ICS.setBad(BadConversionSequence::unrelated_class,
2294 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002295 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002296 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002297
2298 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002299 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002300 ICS.Standard.setAsIdentityConversion();
2301 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002302 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002303 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002304 ICS.Standard.ReferenceBinding = true;
2305 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002306 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002307 return ICS;
2308}
2309
2310/// PerformObjectArgumentInitialization - Perform initialization of
2311/// the implicit object parameter for the given Method with the given
2312/// expression.
2313bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002314Sema::PerformObjectArgumentInitialization(Expr *&From,
2315 NestedNameSpecifier *Qualifier,
2316 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002317 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002318 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002319 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002320
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002321 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002322 FromRecordType = PT->getPointeeType();
2323 DestType = Method->getThisType(Context);
2324 } else {
2325 FromRecordType = From->getType();
2326 DestType = ImplicitParamRecordType;
2327 }
2328
John McCall6e9f8f62009-12-03 04:06:58 +00002329 // Note that we always use the true parent context when performing
2330 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002331 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002332 = TryObjectArgumentInitialization(From->getType(), Method,
2333 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002334 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002335 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002336 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002337 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002338
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002339 if (ICS.Standard.Second == ICK_Derived_To_Base)
2340 return PerformObjectMemberConversion(From, Qualifier, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002341
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002342 if (!Context.hasSameType(From->getType(), DestType))
2343 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2344 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002345 return false;
2346}
2347
Douglas Gregor5fb53972009-01-14 15:45:31 +00002348/// TryContextuallyConvertToBool - Attempt to contextually convert the
2349/// expression From to bool (C++0x [conv]p3).
2350ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002351 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002352 // FIXME: Are these flags correct?
2353 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002354 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002355 /*ForceRValue=*/false,
2356 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002357}
2358
2359/// PerformContextuallyConvertToBool - Perform a contextual conversion
2360/// of the expression From to bool (C++0x [conv]p3).
2361bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2362 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002363 if (!ICS.isBad())
2364 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002365
Fariborz Jahanian76197412009-11-18 18:26:29 +00002366 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002367 return Diag(From->getSourceRange().getBegin(),
2368 diag::err_typecheck_bool_condition)
2369 << From->getType() << From->getSourceRange();
2370 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002371}
2372
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002373/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002374/// candidate functions, using the given function call arguments. If
2375/// @p SuppressUserConversions, then don't allow user-defined
2376/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002377/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2378/// hacky way to implement the overloading rules for elidable copy
2379/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002380///
2381/// \para PartialOverloading true if we are performing "partial" overloading
2382/// based on an incomplete set of function arguments. This feature is used by
2383/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002384void
2385Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCallb89836b2010-01-26 01:37:31 +00002386 AccessSpecifier Access,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002387 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002388 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002389 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002390 bool ForceRValue,
2391 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002392 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002393 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002394 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002395 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002396 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002397
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002399 if (!isa<CXXConstructorDecl>(Method)) {
2400 // If we get here, it's because we're calling a member function
2401 // that is named without a member access expression (e.g.,
2402 // "this->f") that was either written explicitly or created
2403 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002404 // function, e.g., X::f(). We use an empty type for the implied
2405 // object argument (C++ [over.call.func]p3), and the acting context
2406 // is irrelevant.
John McCallb89836b2010-01-26 01:37:31 +00002407 AddMethodCandidate(Method, Access, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002408 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002409 SuppressUserConversions, ForceRValue);
2410 return;
2411 }
2412 // We treat a constructor like a non-member function, since its object
2413 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002414 }
2415
Douglas Gregorff7028a2009-11-13 23:59:09 +00002416 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002417 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002418
Douglas Gregor27381f32009-11-23 12:27:39 +00002419 // Overload resolution is always an unevaluated context.
2420 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2421
Douglas Gregorffe14e32009-11-14 01:20:54 +00002422 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2423 // C++ [class.copy]p3:
2424 // A member function template is never instantiated to perform the copy
2425 // of a class object to an object of its class type.
2426 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2427 if (NumArgs == 1 &&
2428 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002429 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2430 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002431 return;
2432 }
2433
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002434 // Add this candidate
2435 CandidateSet.push_back(OverloadCandidate());
2436 OverloadCandidate& Candidate = CandidateSet.back();
2437 Candidate.Function = Function;
John McCallb89836b2010-01-26 01:37:31 +00002438 Candidate.Access = Access;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002439 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002440 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002441 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002442
2443 unsigned NumArgsInProto = Proto->getNumArgs();
2444
2445 // (C++ 13.3.2p2): A candidate function having fewer than m
2446 // parameters is viable only if it has an ellipsis in its parameter
2447 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002448 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2449 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002450 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002451 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002452 return;
2453 }
2454
2455 // (C++ 13.3.2p2): A candidate function having more than m parameters
2456 // is viable only if the (m+1)st parameter has a default argument
2457 // (8.3.6). For the purposes of overload resolution, the
2458 // parameter list is truncated on the right, so that there are
2459 // exactly m parameters.
2460 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002461 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002462 // Not enough arguments.
2463 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002464 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002465 return;
2466 }
2467
2468 // Determine the implicit conversion sequences for each of the
2469 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002470 Candidate.Conversions.resize(NumArgs);
2471 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2472 if (ArgIdx < NumArgsInProto) {
2473 // (C++ 13.3.2p3): for F to be a viable function, there shall
2474 // exist for each argument an implicit conversion sequence
2475 // (13.3.3.1) that converts that argument to the corresponding
2476 // parameter of F.
2477 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002478 Candidate.Conversions[ArgIdx]
2479 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002480 SuppressUserConversions, ForceRValue,
2481 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002482 if (Candidate.Conversions[ArgIdx].isBad()) {
2483 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002484 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002485 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002486 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002487 } else {
2488 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2489 // argument for which there is no corresponding parameter is
2490 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002491 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002492 }
2493 }
2494}
2495
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002496/// \brief Add all of the function declarations in the given function set to
2497/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002498void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002499 Expr **Args, unsigned NumArgs,
2500 OverloadCandidateSet& CandidateSet,
2501 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002502 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002503 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2505 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002506 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002507 cast<CXXMethodDecl>(FD)->getParent(),
2508 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002509 CandidateSet, SuppressUserConversions);
2510 else
John McCallb89836b2010-01-26 01:37:31 +00002511 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002512 SuppressUserConversions);
2513 } else {
2514 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2515 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2516 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002517 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002518 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002519 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002520 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002521 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002522 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002523 else
John McCallb89836b2010-01-26 01:37:31 +00002524 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCall6b51f282009-11-23 01:53:49 +00002525 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002526 Args, NumArgs, CandidateSet,
2527 SuppressUserConversions);
2528 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002529 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002530}
2531
John McCallf0f1cf02009-11-17 07:50:12 +00002532/// AddMethodCandidate - Adds a named decl (which is some kind of
2533/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002534void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCallb89836b2010-01-26 01:37:31 +00002535 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002536 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002537 Expr **Args, unsigned NumArgs,
2538 OverloadCandidateSet& CandidateSet,
2539 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002540 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002541
2542 if (isa<UsingShadowDecl>(Decl))
2543 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2544
2545 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2546 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2547 "Expected a member function template");
John McCallb89836b2010-01-26 01:37:31 +00002548 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002549 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002550 CandidateSet,
2551 SuppressUserConversions,
2552 ForceRValue);
2553 } else {
John McCallb89836b2010-01-26 01:37:31 +00002554 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002555 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002556 CandidateSet, SuppressUserConversions, ForceRValue);
2557 }
2558}
2559
Douglas Gregor436424c2008-11-18 23:14:02 +00002560/// AddMethodCandidate - Adds the given C++ member function to the set
2561/// of candidate functions, using the given function call arguments
2562/// and the object argument (@c Object). For example, in a call
2563/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2564/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2565/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002566/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2567/// a slightly hacky way to implement the overloading rules for elidable copy
2568/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002569void
John McCallb89836b2010-01-26 01:37:31 +00002570Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2571 CXXRecordDecl *ActingContext, QualType ObjectType,
2572 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002573 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002574 bool SuppressUserConversions, bool ForceRValue) {
2575 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002576 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002577 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002578 assert(!isa<CXXConstructorDecl>(Method) &&
2579 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002580
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002581 if (!CandidateSet.isNewCandidate(Method))
2582 return;
2583
Douglas Gregor27381f32009-11-23 12:27:39 +00002584 // Overload resolution is always an unevaluated context.
2585 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2586
Douglas Gregor436424c2008-11-18 23:14:02 +00002587 // Add this candidate
2588 CandidateSet.push_back(OverloadCandidate());
2589 OverloadCandidate& Candidate = CandidateSet.back();
2590 Candidate.Function = Method;
John McCallb89836b2010-01-26 01:37:31 +00002591 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002592 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002593 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002594
2595 unsigned NumArgsInProto = Proto->getNumArgs();
2596
2597 // (C++ 13.3.2p2): A candidate function having fewer than m
2598 // parameters is viable only if it has an ellipsis in its parameter
2599 // list (8.3.5).
2600 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2601 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002602 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002603 return;
2604 }
2605
2606 // (C++ 13.3.2p2): A candidate function having more than m parameters
2607 // is viable only if the (m+1)st parameter has a default argument
2608 // (8.3.6). For the purposes of overload resolution, the
2609 // parameter list is truncated on the right, so that there are
2610 // exactly m parameters.
2611 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2612 if (NumArgs < MinRequiredArgs) {
2613 // Not enough arguments.
2614 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002615 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002616 return;
2617 }
2618
2619 Candidate.Viable = true;
2620 Candidate.Conversions.resize(NumArgs + 1);
2621
John McCall6e9f8f62009-12-03 04:06:58 +00002622 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002623 // The implicit object argument is ignored.
2624 Candidate.IgnoreObjectArgument = true;
2625 else {
2626 // Determine the implicit conversion sequence for the object
2627 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002628 Candidate.Conversions[0]
2629 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002630 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002631 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002632 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002633 return;
2634 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002635 }
2636
2637 // Determine the implicit conversion sequences for each of the
2638 // arguments.
2639 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2640 if (ArgIdx < NumArgsInProto) {
2641 // (C++ 13.3.2p3): for F to be a viable function, there shall
2642 // exist for each argument an implicit conversion sequence
2643 // (13.3.3.1) that converts that argument to the corresponding
2644 // parameter of F.
2645 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002646 Candidate.Conversions[ArgIdx + 1]
2647 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002648 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002649 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002650 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002651 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002652 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002653 break;
2654 }
2655 } else {
2656 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2657 // argument for which there is no corresponding parameter is
2658 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002659 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002660 }
2661 }
2662}
2663
Douglas Gregor97628d62009-08-21 00:16:32 +00002664/// \brief Add a C++ member function template as a candidate to the candidate
2665/// set, using template argument deduction to produce an appropriate member
2666/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002667void
Douglas Gregor97628d62009-08-21 00:16:32 +00002668Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCallb89836b2010-01-26 01:37:31 +00002669 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002670 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002671 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002672 QualType ObjectType,
2673 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002674 OverloadCandidateSet& CandidateSet,
2675 bool SuppressUserConversions,
2676 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002677 if (!CandidateSet.isNewCandidate(MethodTmpl))
2678 return;
2679
Douglas Gregor97628d62009-08-21 00:16:32 +00002680 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002681 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002682 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002683 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002684 // candidate functions in the usual way.113) A given name can refer to one
2685 // or more function templates and also to a set of overloaded non-template
2686 // functions. In such a case, the candidate functions generated from each
2687 // function template are combined with the set of non-template candidate
2688 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002689 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00002690 FunctionDecl *Specialization = 0;
2691 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002692 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002693 Args, NumArgs, Specialization, Info)) {
2694 // FIXME: Record what happened with template argument deduction, so
2695 // that we can give the user a beautiful diagnostic.
2696 (void)Result;
2697 return;
2698 }
Mike Stump11289f42009-09-09 15:08:12 +00002699
Douglas Gregor97628d62009-08-21 00:16:32 +00002700 // Add the function template specialization produced by template argument
2701 // deduction as a candidate.
2702 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002703 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002704 "Specialization is not a member function?");
John McCallb89836b2010-01-26 01:37:31 +00002705 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2706 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002707 CandidateSet, SuppressUserConversions, ForceRValue);
2708}
2709
Douglas Gregor05155d82009-08-21 23:19:43 +00002710/// \brief Add a C++ function template specialization as a candidate
2711/// in the candidate set, using template argument deduction to produce
2712/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002713void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002714Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002715 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00002716 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002717 Expr **Args, unsigned NumArgs,
2718 OverloadCandidateSet& CandidateSet,
2719 bool SuppressUserConversions,
2720 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002721 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2722 return;
2723
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002724 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002725 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002726 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002727 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002728 // candidate functions in the usual way.113) A given name can refer to one
2729 // or more function templates and also to a set of overloaded non-template
2730 // functions. In such a case, the candidate functions generated from each
2731 // function template are combined with the set of non-template candidate
2732 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002733 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002734 FunctionDecl *Specialization = 0;
2735 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002736 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002737 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00002738 CandidateSet.push_back(OverloadCandidate());
2739 OverloadCandidate &Candidate = CandidateSet.back();
2740 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCallb89836b2010-01-26 01:37:31 +00002741 Candidate.Access = Access;
John McCalld681c392009-12-16 08:11:27 +00002742 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002743 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002744 Candidate.IsSurrogate = false;
2745 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00002746
2747 // TODO: record more information about failed template arguments
2748 Candidate.DeductionFailure.Result = Result;
2749 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002750 return;
2751 }
Mike Stump11289f42009-09-09 15:08:12 +00002752
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002753 // Add the function template specialization produced by template argument
2754 // deduction as a candidate.
2755 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002756 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002757 SuppressUserConversions, ForceRValue);
2758}
Mike Stump11289f42009-09-09 15:08:12 +00002759
Douglas Gregora1f013e2008-11-07 22:36:19 +00002760/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002761/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002762/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002763/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002764/// (which may or may not be the same type as the type that the
2765/// conversion function produces).
2766void
2767Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002768 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002769 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002770 Expr *From, QualType ToType,
2771 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002772 assert(!Conversion->getDescribedFunctionTemplate() &&
2773 "Conversion function templates use AddTemplateConversionCandidate");
2774
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002775 if (!CandidateSet.isNewCandidate(Conversion))
2776 return;
2777
Douglas Gregor27381f32009-11-23 12:27:39 +00002778 // Overload resolution is always an unevaluated context.
2779 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2780
Douglas Gregora1f013e2008-11-07 22:36:19 +00002781 // Add this candidate
2782 CandidateSet.push_back(OverloadCandidate());
2783 OverloadCandidate& Candidate = CandidateSet.back();
2784 Candidate.Function = Conversion;
John McCallb89836b2010-01-26 01:37:31 +00002785 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002786 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002787 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002788 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002789 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002790 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002791
Douglas Gregor436424c2008-11-18 23:14:02 +00002792 // Determine the implicit conversion sequence for the implicit
2793 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002794 Candidate.Viable = true;
2795 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002796 Candidate.Conversions[0]
2797 = TryObjectArgumentInitialization(From->getType(), Conversion,
2798 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002799 // Conversion functions to a different type in the base class is visible in
2800 // the derived class. So, a derived to base conversion should not participate
2801 // in overload resolution.
2802 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2803 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002804 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002805 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002806 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002807 return;
2808 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002809
2810 // We won't go through a user-define type conversion function to convert a
2811 // derived to base as such conversions are given Conversion Rank. They only
2812 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2813 QualType FromCanon
2814 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2815 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2816 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2817 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002818 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002819 return;
2820 }
2821
Douglas Gregora1f013e2008-11-07 22:36:19 +00002822
2823 // To determine what the conversion from the result of calling the
2824 // conversion function to the type we're eventually trying to
2825 // convert to (ToType), we need to synthesize a call to the
2826 // conversion function and attempt copy initialization from it. This
2827 // makes sure that we get the right semantics with respect to
2828 // lvalues/rvalues and the type. Fortunately, we can allocate this
2829 // call on the stack and we don't need its arguments to be
2830 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002831 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002832 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002833 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002834 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002835 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002836
2837 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002838 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2839 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002840 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002841 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002842 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002843 ImplicitConversionSequence ICS =
2844 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002845 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002846 /*ForceRValue=*/false,
2847 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002848
John McCall0d1da222010-01-12 00:44:57 +00002849 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002850 case ImplicitConversionSequence::StandardConversion:
2851 Candidate.FinalConversion = ICS.Standard;
2852 break;
2853
2854 case ImplicitConversionSequence::BadConversion:
2855 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002856 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002857 break;
2858
2859 default:
Mike Stump11289f42009-09-09 15:08:12 +00002860 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002861 "Can only end up with a standard conversion sequence or failure");
2862 }
2863}
2864
Douglas Gregor05155d82009-08-21 23:19:43 +00002865/// \brief Adds a conversion function template specialization
2866/// candidate to the overload set, using template argument deduction
2867/// to deduce the template arguments of the conversion function
2868/// template from the type that we are converting to (C++
2869/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002870void
Douglas Gregor05155d82009-08-21 23:19:43 +00002871Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002872 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002873 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002874 Expr *From, QualType ToType,
2875 OverloadCandidateSet &CandidateSet) {
2876 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2877 "Only conversion function templates permitted here");
2878
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002879 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2880 return;
2881
John McCallbc077cf2010-02-08 23:07:23 +00002882 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00002883 CXXConversionDecl *Specialization = 0;
2884 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002885 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002886 Specialization, Info)) {
2887 // FIXME: Record what happened with template argument deduction, so
2888 // that we can give the user a beautiful diagnostic.
2889 (void)Result;
2890 return;
2891 }
Mike Stump11289f42009-09-09 15:08:12 +00002892
Douglas Gregor05155d82009-08-21 23:19:43 +00002893 // Add the conversion function template specialization produced by
2894 // template argument deduction as a candidate.
2895 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002896 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2897 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002898}
2899
Douglas Gregorab7897a2008-11-19 22:57:39 +00002900/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2901/// converts the given @c Object to a function pointer via the
2902/// conversion function @c Conversion, and then attempts to call it
2903/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2904/// the type of function that we'll eventually be calling.
2905void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002906 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002907 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002908 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002909 QualType ObjectType,
2910 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002911 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002912 if (!CandidateSet.isNewCandidate(Conversion))
2913 return;
2914
Douglas Gregor27381f32009-11-23 12:27:39 +00002915 // Overload resolution is always an unevaluated context.
2916 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2917
Douglas Gregorab7897a2008-11-19 22:57:39 +00002918 CandidateSet.push_back(OverloadCandidate());
2919 OverloadCandidate& Candidate = CandidateSet.back();
2920 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00002921 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002922 Candidate.Surrogate = Conversion;
2923 Candidate.Viable = true;
2924 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002925 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002926 Candidate.Conversions.resize(NumArgs + 1);
2927
2928 // Determine the implicit conversion sequence for the implicit
2929 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002930 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002931 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002932 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002933 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002934 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00002935 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002936 return;
2937 }
2938
2939 // The first conversion is actually a user-defined conversion whose
2940 // first conversion is ObjectInit's standard conversion (which is
2941 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002942 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002943 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002944 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002945 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002946 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002947 = Candidate.Conversions[0].UserDefined.Before;
2948 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2949
Mike Stump11289f42009-09-09 15:08:12 +00002950 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002951 unsigned NumArgsInProto = Proto->getNumArgs();
2952
2953 // (C++ 13.3.2p2): A candidate function having fewer than m
2954 // parameters is viable only if it has an ellipsis in its parameter
2955 // list (8.3.5).
2956 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2957 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002958 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002959 return;
2960 }
2961
2962 // Function types don't have any default arguments, so just check if
2963 // we have enough arguments.
2964 if (NumArgs < NumArgsInProto) {
2965 // Not enough arguments.
2966 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002967 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002968 return;
2969 }
2970
2971 // Determine the implicit conversion sequences for each of the
2972 // arguments.
2973 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2974 if (ArgIdx < NumArgsInProto) {
2975 // (C++ 13.3.2p3): for F to be a viable function, there shall
2976 // exist for each argument an implicit conversion sequence
2977 // (13.3.3.1) that converts that argument to the corresponding
2978 // parameter of F.
2979 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002980 Candidate.Conversions[ArgIdx + 1]
2981 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002982 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002983 /*ForceRValue=*/false,
2984 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002985 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002986 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002987 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002988 break;
2989 }
2990 } else {
2991 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2992 // argument for which there is no corresponding parameter is
2993 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002994 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002995 }
2996 }
2997}
2998
Mike Stump87c57ac2009-05-16 07:39:55 +00002999// FIXME: This will eventually be removed, once we've migrated all of the
3000// operator overloading logic over to the scheme used by binary operators, which
3001// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003002void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003003 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003004 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003005 OverloadCandidateSet& CandidateSet,
3006 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003007 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003008
3009 QualType T1 = Args[0]->getType();
3010 QualType T2;
3011 if (NumArgs > 1)
3012 T2 = Args[1]->getType();
3013
3014 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003015 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003016 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3017 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3018 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3019 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003020 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003021 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003022}
3023
3024/// \brief Add overload candidates for overloaded operators that are
3025/// member functions.
3026///
3027/// Add the overloaded operator candidates that are member functions
3028/// for the operator Op that was used in an operator expression such
3029/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3030/// CandidateSet will store the added overload candidates. (C++
3031/// [over.match.oper]).
3032void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3033 SourceLocation OpLoc,
3034 Expr **Args, unsigned NumArgs,
3035 OverloadCandidateSet& CandidateSet,
3036 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003037 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3038
3039 // C++ [over.match.oper]p3:
3040 // For a unary operator @ with an operand of a type whose
3041 // cv-unqualified version is T1, and for a binary operator @ with
3042 // a left operand of a type whose cv-unqualified version is T1 and
3043 // a right operand of a type whose cv-unqualified version is T2,
3044 // three sets of candidate functions, designated member
3045 // candidates, non-member candidates and built-in candidates, are
3046 // constructed as follows:
3047 QualType T1 = Args[0]->getType();
3048 QualType T2;
3049 if (NumArgs > 1)
3050 T2 = Args[1]->getType();
3051
3052 // -- If T1 is a class type, the set of member candidates is the
3053 // result of the qualified lookup of T1::operator@
3054 // (13.3.1.1.1); otherwise, the set of member candidates is
3055 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003056 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003057 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003058 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003059 return;
Mike Stump11289f42009-09-09 15:08:12 +00003060
John McCall27b18f82009-11-17 02:14:36 +00003061 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3062 LookupQualifiedName(Operators, T1Rec->getDecl());
3063 Operators.suppressDiagnostics();
3064
Mike Stump11289f42009-09-09 15:08:12 +00003065 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003066 OperEnd = Operators.end();
3067 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003068 ++Oper)
John McCallb89836b2010-01-26 01:37:31 +00003069 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003070 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003071 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003072 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003073}
3074
Douglas Gregora11693b2008-11-12 17:17:38 +00003075/// AddBuiltinCandidate - Add a candidate for a built-in
3076/// operator. ResultTy and ParamTys are the result and parameter types
3077/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003078/// arguments being passed to the candidate. IsAssignmentOperator
3079/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003080/// operator. NumContextualBoolArguments is the number of arguments
3081/// (at the beginning of the argument list) that will be contextually
3082/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003083void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003084 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003085 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003086 bool IsAssignmentOperator,
3087 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003088 // Overload resolution is always an unevaluated context.
3089 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3090
Douglas Gregora11693b2008-11-12 17:17:38 +00003091 // Add this candidate
3092 CandidateSet.push_back(OverloadCandidate());
3093 OverloadCandidate& Candidate = CandidateSet.back();
3094 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00003095 Candidate.Access = AS_none;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003096 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003097 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003098 Candidate.BuiltinTypes.ResultTy = ResultTy;
3099 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3100 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3101
3102 // Determine the implicit conversion sequences for each of the
3103 // arguments.
3104 Candidate.Viable = true;
3105 Candidate.Conversions.resize(NumArgs);
3106 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003107 // C++ [over.match.oper]p4:
3108 // For the built-in assignment operators, conversions of the
3109 // left operand are restricted as follows:
3110 // -- no temporaries are introduced to hold the left operand, and
3111 // -- no user-defined conversions are applied to the left
3112 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003113 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003114 //
3115 // We block these conversions by turning off user-defined
3116 // conversions, since that is the only way that initialization of
3117 // a reference to a non-class type can occur from something that
3118 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003119 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003120 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003121 "Contextual conversion to bool requires bool type");
3122 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3123 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003124 Candidate.Conversions[ArgIdx]
3125 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003126 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003127 /*ForceRValue=*/false,
3128 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003129 }
John McCall0d1da222010-01-12 00:44:57 +00003130 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003131 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003132 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003133 break;
3134 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003135 }
3136}
3137
3138/// BuiltinCandidateTypeSet - A set of types that will be used for the
3139/// candidate operator functions for built-in operators (C++
3140/// [over.built]). The types are separated into pointer types and
3141/// enumeration types.
3142class BuiltinCandidateTypeSet {
3143 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003144 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003145
3146 /// PointerTypes - The set of pointer types that will be used in the
3147 /// built-in candidates.
3148 TypeSet PointerTypes;
3149
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003150 /// MemberPointerTypes - The set of member pointer types that will be
3151 /// used in the built-in candidates.
3152 TypeSet MemberPointerTypes;
3153
Douglas Gregora11693b2008-11-12 17:17:38 +00003154 /// EnumerationTypes - The set of enumeration types that will be
3155 /// used in the built-in candidates.
3156 TypeSet EnumerationTypes;
3157
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003158 /// Sema - The semantic analysis instance where we are building the
3159 /// candidate type set.
3160 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003161
Douglas Gregora11693b2008-11-12 17:17:38 +00003162 /// Context - The AST context in which we will build the type sets.
3163 ASTContext &Context;
3164
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003165 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3166 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003167 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003168
3169public:
3170 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003171 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003172
Mike Stump11289f42009-09-09 15:08:12 +00003173 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003174 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003175
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003176 void AddTypesConvertedFrom(QualType Ty,
3177 SourceLocation Loc,
3178 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003179 bool AllowExplicitConversions,
3180 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003181
3182 /// pointer_begin - First pointer type found;
3183 iterator pointer_begin() { return PointerTypes.begin(); }
3184
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003185 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003186 iterator pointer_end() { return PointerTypes.end(); }
3187
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003188 /// member_pointer_begin - First member pointer type found;
3189 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3190
3191 /// member_pointer_end - Past the last member pointer type found;
3192 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3193
Douglas Gregora11693b2008-11-12 17:17:38 +00003194 /// enumeration_begin - First enumeration type found;
3195 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3196
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003197 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003198 iterator enumeration_end() { return EnumerationTypes.end(); }
3199};
3200
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003201/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003202/// the set of pointer types along with any more-qualified variants of
3203/// that type. For example, if @p Ty is "int const *", this routine
3204/// will add "int const *", "int const volatile *", "int const
3205/// restrict *", and "int const volatile restrict *" to the set of
3206/// pointer types. Returns true if the add of @p Ty itself succeeded,
3207/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003208///
3209/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003210bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003211BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3212 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003213
Douglas Gregora11693b2008-11-12 17:17:38 +00003214 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003215 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003216 return false;
3217
John McCall8ccfcb52009-09-24 19:53:00 +00003218 const PointerType *PointerTy = Ty->getAs<PointerType>();
3219 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003220
John McCall8ccfcb52009-09-24 19:53:00 +00003221 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003222 // Don't add qualified variants of arrays. For one, they're not allowed
3223 // (the qualifier would sink to the element type), and for another, the
3224 // only overload situation where it matters is subscript or pointer +- int,
3225 // and those shouldn't have qualifier variants anyway.
3226 if (PointeeTy->isArrayType())
3227 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003228 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003229 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003230 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003231 bool hasVolatile = VisibleQuals.hasVolatile();
3232 bool hasRestrict = VisibleQuals.hasRestrict();
3233
John McCall8ccfcb52009-09-24 19:53:00 +00003234 // Iterate through all strict supersets of BaseCVR.
3235 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3236 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003237 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3238 // in the types.
3239 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3240 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003241 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3242 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003243 }
3244
3245 return true;
3246}
3247
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003248/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3249/// to the set of pointer types along with any more-qualified variants of
3250/// that type. For example, if @p Ty is "int const *", this routine
3251/// will add "int const *", "int const volatile *", "int const
3252/// restrict *", and "int const volatile restrict *" to the set of
3253/// pointer types. Returns true if the add of @p Ty itself succeeded,
3254/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003255///
3256/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003257bool
3258BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3259 QualType Ty) {
3260 // Insert this type.
3261 if (!MemberPointerTypes.insert(Ty))
3262 return false;
3263
John McCall8ccfcb52009-09-24 19:53:00 +00003264 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3265 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003266
John McCall8ccfcb52009-09-24 19:53:00 +00003267 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003268 // Don't add qualified variants of arrays. For one, they're not allowed
3269 // (the qualifier would sink to the element type), and for another, the
3270 // only overload situation where it matters is subscript or pointer +- int,
3271 // and those shouldn't have qualifier variants anyway.
3272 if (PointeeTy->isArrayType())
3273 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003274 const Type *ClassTy = PointerTy->getClass();
3275
3276 // Iterate through all strict supersets of the pointee type's CVR
3277 // qualifiers.
3278 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3279 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3280 if ((CVR | BaseCVR) != CVR) continue;
3281
3282 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3283 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003284 }
3285
3286 return true;
3287}
3288
Douglas Gregora11693b2008-11-12 17:17:38 +00003289/// AddTypesConvertedFrom - Add each of the types to which the type @p
3290/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003291/// primarily interested in pointer types and enumeration types. We also
3292/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003293/// AllowUserConversions is true if we should look at the conversion
3294/// functions of a class type, and AllowExplicitConversions if we
3295/// should also include the explicit conversion functions of a class
3296/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003297void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003298BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003299 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003300 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003301 bool AllowExplicitConversions,
3302 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003303 // Only deal with canonical types.
3304 Ty = Context.getCanonicalType(Ty);
3305
3306 // Look through reference types; they aren't part of the type of an
3307 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003308 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003309 Ty = RefTy->getPointeeType();
3310
3311 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003312 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003313
Sebastian Redl65ae2002009-11-05 16:36:20 +00003314 // If we're dealing with an array type, decay to the pointer.
3315 if (Ty->isArrayType())
3316 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3317
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003318 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003319 QualType PointeeTy = PointerTy->getPointeeType();
3320
3321 // Insert our type, and its more-qualified variants, into the set
3322 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003323 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003324 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003325 } else if (Ty->isMemberPointerType()) {
3326 // Member pointers are far easier, since the pointee can't be converted.
3327 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3328 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003329 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003330 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003331 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003332 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003333 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003334 // No conversion functions in incomplete types.
3335 return;
3336 }
Mike Stump11289f42009-09-09 15:08:12 +00003337
Douglas Gregora11693b2008-11-12 17:17:38 +00003338 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003339 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003340 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003341 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003342 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003343
Mike Stump11289f42009-09-09 15:08:12 +00003344 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003345 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003346 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003347 continue;
3348
John McCalld14a8642009-11-21 08:51:07 +00003349 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003350 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003351 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003352 VisibleQuals);
3353 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003354 }
3355 }
3356 }
3357}
3358
Douglas Gregor84605ae2009-08-24 13:43:27 +00003359/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3360/// the volatile- and non-volatile-qualified assignment operators for the
3361/// given type to the candidate set.
3362static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3363 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003364 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003365 unsigned NumArgs,
3366 OverloadCandidateSet &CandidateSet) {
3367 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003368
Douglas Gregor84605ae2009-08-24 13:43:27 +00003369 // T& operator=(T&, T)
3370 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3371 ParamTypes[1] = T;
3372 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3373 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003374
Douglas Gregor84605ae2009-08-24 13:43:27 +00003375 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3376 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003377 ParamTypes[0]
3378 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003379 ParamTypes[1] = T;
3380 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003381 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003382 }
3383}
Mike Stump11289f42009-09-09 15:08:12 +00003384
Sebastian Redl1054fae2009-10-25 17:03:50 +00003385/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3386/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003387static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3388 Qualifiers VRQuals;
3389 const RecordType *TyRec;
3390 if (const MemberPointerType *RHSMPType =
3391 ArgExpr->getType()->getAs<MemberPointerType>())
3392 TyRec = cast<RecordType>(RHSMPType->getClass());
3393 else
3394 TyRec = ArgExpr->getType()->getAs<RecordType>();
3395 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003396 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003397 VRQuals.addVolatile();
3398 VRQuals.addRestrict();
3399 return VRQuals;
3400 }
3401
3402 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003403 if (!ClassDecl->hasDefinition())
3404 return VRQuals;
3405
John McCallad371252010-01-20 00:46:10 +00003406 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003407 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003408
John McCallad371252010-01-20 00:46:10 +00003409 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003410 E = Conversions->end(); I != E; ++I) {
3411 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003412 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3413 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3414 CanTy = ResTypeRef->getPointeeType();
3415 // Need to go down the pointer/mempointer chain and add qualifiers
3416 // as see them.
3417 bool done = false;
3418 while (!done) {
3419 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3420 CanTy = ResTypePtr->getPointeeType();
3421 else if (const MemberPointerType *ResTypeMPtr =
3422 CanTy->getAs<MemberPointerType>())
3423 CanTy = ResTypeMPtr->getPointeeType();
3424 else
3425 done = true;
3426 if (CanTy.isVolatileQualified())
3427 VRQuals.addVolatile();
3428 if (CanTy.isRestrictQualified())
3429 VRQuals.addRestrict();
3430 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3431 return VRQuals;
3432 }
3433 }
3434 }
3435 return VRQuals;
3436}
3437
Douglas Gregord08452f2008-11-19 15:42:04 +00003438/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3439/// operator overloads to the candidate set (C++ [over.built]), based
3440/// on the operator @p Op and the arguments given. For example, if the
3441/// operator is a binary '+', this routine might add "int
3442/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003443void
Mike Stump11289f42009-09-09 15:08:12 +00003444Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003445 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003446 Expr **Args, unsigned NumArgs,
3447 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003448 // The set of "promoted arithmetic types", which are the arithmetic
3449 // types are that preserved by promotion (C++ [over.built]p2). Note
3450 // that the first few of these types are the promoted integral
3451 // types; these types need to be first.
3452 // FIXME: What about complex?
3453 const unsigned FirstIntegralType = 0;
3454 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003455 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003456 LastPromotedIntegralType = 13;
3457 const unsigned FirstPromotedArithmeticType = 7,
3458 LastPromotedArithmeticType = 16;
3459 const unsigned NumArithmeticTypes = 16;
3460 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003461 Context.BoolTy, Context.CharTy, Context.WCharTy,
3462// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003463 Context.SignedCharTy, Context.ShortTy,
3464 Context.UnsignedCharTy, Context.UnsignedShortTy,
3465 Context.IntTy, Context.LongTy, Context.LongLongTy,
3466 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3467 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3468 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003469 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3470 "Invalid first promoted integral type");
3471 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3472 == Context.UnsignedLongLongTy &&
3473 "Invalid last promoted integral type");
3474 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3475 "Invalid first promoted arithmetic type");
3476 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3477 == Context.LongDoubleTy &&
3478 "Invalid last promoted arithmetic type");
3479
Douglas Gregora11693b2008-11-12 17:17:38 +00003480 // Find all of the types that the arguments can convert to, but only
3481 // if the operator we're looking at has built-in operator candidates
3482 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003483 Qualifiers VisibleTypeConversionsQuals;
3484 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003485 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3486 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3487
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003488 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003489 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3490 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003491 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003492 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003493 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003494 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003495 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003496 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003497 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003498 true,
3499 (Op == OO_Exclaim ||
3500 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003501 Op == OO_PipePipe),
3502 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003503 }
3504
3505 bool isComparison = false;
3506 switch (Op) {
3507 case OO_None:
3508 case NUM_OVERLOADED_OPERATORS:
3509 assert(false && "Expected an overloaded operator");
3510 break;
3511
Douglas Gregord08452f2008-11-19 15:42:04 +00003512 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003513 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003514 goto UnaryStar;
3515 else
3516 goto BinaryStar;
3517 break;
3518
3519 case OO_Plus: // '+' is either unary or binary
3520 if (NumArgs == 1)
3521 goto UnaryPlus;
3522 else
3523 goto BinaryPlus;
3524 break;
3525
3526 case OO_Minus: // '-' is either unary or binary
3527 if (NumArgs == 1)
3528 goto UnaryMinus;
3529 else
3530 goto BinaryMinus;
3531 break;
3532
3533 case OO_Amp: // '&' is either unary or binary
3534 if (NumArgs == 1)
3535 goto UnaryAmp;
3536 else
3537 goto BinaryAmp;
3538
3539 case OO_PlusPlus:
3540 case OO_MinusMinus:
3541 // C++ [over.built]p3:
3542 //
3543 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3544 // is either volatile or empty, there exist candidate operator
3545 // functions of the form
3546 //
3547 // VQ T& operator++(VQ T&);
3548 // T operator++(VQ T&, int);
3549 //
3550 // C++ [over.built]p4:
3551 //
3552 // For every pair (T, VQ), where T is an arithmetic type other
3553 // than bool, and VQ is either volatile or empty, there exist
3554 // candidate operator functions of the form
3555 //
3556 // VQ T& operator--(VQ T&);
3557 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003558 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003559 Arith < NumArithmeticTypes; ++Arith) {
3560 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003561 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003562 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003563
3564 // Non-volatile version.
3565 if (NumArgs == 1)
3566 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3567 else
3568 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003569 // heuristic to reduce number of builtin candidates in the set.
3570 // Add volatile version only if there are conversions to a volatile type.
3571 if (VisibleTypeConversionsQuals.hasVolatile()) {
3572 // Volatile version
3573 ParamTypes[0]
3574 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3575 if (NumArgs == 1)
3576 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3577 else
3578 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3579 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003580 }
3581
3582 // C++ [over.built]p5:
3583 //
3584 // For every pair (T, VQ), where T is a cv-qualified or
3585 // cv-unqualified object type, and VQ is either volatile or
3586 // empty, there exist candidate operator functions of the form
3587 //
3588 // T*VQ& operator++(T*VQ&);
3589 // T*VQ& operator--(T*VQ&);
3590 // T* operator++(T*VQ&, int);
3591 // T* operator--(T*VQ&, int);
3592 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3593 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3594 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003595 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003596 continue;
3597
Mike Stump11289f42009-09-09 15:08:12 +00003598 QualType ParamTypes[2] = {
3599 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003600 };
Mike Stump11289f42009-09-09 15:08:12 +00003601
Douglas Gregord08452f2008-11-19 15:42:04 +00003602 // Without volatile
3603 if (NumArgs == 1)
3604 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3605 else
3606 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3607
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003608 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3609 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003610 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003611 ParamTypes[0]
3612 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003613 if (NumArgs == 1)
3614 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3615 else
3616 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3617 }
3618 }
3619 break;
3620
3621 UnaryStar:
3622 // C++ [over.built]p6:
3623 // For every cv-qualified or cv-unqualified object type T, there
3624 // exist candidate operator functions of the form
3625 //
3626 // T& operator*(T*);
3627 //
3628 // C++ [over.built]p7:
3629 // For every function type T, there exist candidate operator
3630 // functions of the form
3631 // T& operator*(T*);
3632 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3633 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3634 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003635 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003636 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003637 &ParamTy, Args, 1, CandidateSet);
3638 }
3639 break;
3640
3641 UnaryPlus:
3642 // C++ [over.built]p8:
3643 // For every type T, there exist candidate operator functions of
3644 // the form
3645 //
3646 // T* operator+(T*);
3647 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3648 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3649 QualType ParamTy = *Ptr;
3650 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3651 }
Mike Stump11289f42009-09-09 15:08:12 +00003652
Douglas Gregord08452f2008-11-19 15:42:04 +00003653 // Fall through
3654
3655 UnaryMinus:
3656 // C++ [over.built]p9:
3657 // For every promoted arithmetic type T, there exist candidate
3658 // operator functions of the form
3659 //
3660 // T operator+(T);
3661 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003662 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003663 Arith < LastPromotedArithmeticType; ++Arith) {
3664 QualType ArithTy = ArithmeticTypes[Arith];
3665 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3666 }
3667 break;
3668
3669 case OO_Tilde:
3670 // C++ [over.built]p10:
3671 // For every promoted integral type T, there exist candidate
3672 // operator functions of the form
3673 //
3674 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003675 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003676 Int < LastPromotedIntegralType; ++Int) {
3677 QualType IntTy = ArithmeticTypes[Int];
3678 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3679 }
3680 break;
3681
Douglas Gregora11693b2008-11-12 17:17:38 +00003682 case OO_New:
3683 case OO_Delete:
3684 case OO_Array_New:
3685 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003686 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003687 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003688 break;
3689
3690 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003691 UnaryAmp:
3692 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003693 // C++ [over.match.oper]p3:
3694 // -- For the operator ',', the unary operator '&', or the
3695 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003696 break;
3697
Douglas Gregor84605ae2009-08-24 13:43:27 +00003698 case OO_EqualEqual:
3699 case OO_ExclaimEqual:
3700 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003701 // For every pointer to member type T, there exist candidate operator
3702 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003703 //
3704 // bool operator==(T,T);
3705 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003706 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003707 MemPtr = CandidateTypes.member_pointer_begin(),
3708 MemPtrEnd = CandidateTypes.member_pointer_end();
3709 MemPtr != MemPtrEnd;
3710 ++MemPtr) {
3711 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3712 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3713 }
Mike Stump11289f42009-09-09 15:08:12 +00003714
Douglas Gregor84605ae2009-08-24 13:43:27 +00003715 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003716
Douglas Gregora11693b2008-11-12 17:17:38 +00003717 case OO_Less:
3718 case OO_Greater:
3719 case OO_LessEqual:
3720 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003721 // C++ [over.built]p15:
3722 //
3723 // For every pointer or enumeration type T, there exist
3724 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003725 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003726 // bool operator<(T, T);
3727 // bool operator>(T, T);
3728 // bool operator<=(T, T);
3729 // bool operator>=(T, T);
3730 // bool operator==(T, T);
3731 // bool operator!=(T, T);
3732 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3733 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3734 QualType ParamTypes[2] = { *Ptr, *Ptr };
3735 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3736 }
Mike Stump11289f42009-09-09 15:08:12 +00003737 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003738 = CandidateTypes.enumeration_begin();
3739 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3740 QualType ParamTypes[2] = { *Enum, *Enum };
3741 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3742 }
3743
3744 // Fall through.
3745 isComparison = true;
3746
Douglas Gregord08452f2008-11-19 15:42:04 +00003747 BinaryPlus:
3748 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003749 if (!isComparison) {
3750 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3751
3752 // C++ [over.built]p13:
3753 //
3754 // For every cv-qualified or cv-unqualified object type T
3755 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003756 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003757 // T* operator+(T*, ptrdiff_t);
3758 // T& operator[](T*, ptrdiff_t); [BELOW]
3759 // T* operator-(T*, ptrdiff_t);
3760 // T* operator+(ptrdiff_t, T*);
3761 // T& operator[](ptrdiff_t, T*); [BELOW]
3762 //
3763 // C++ [over.built]p14:
3764 //
3765 // For every T, where T is a pointer to object type, there
3766 // exist candidate operator functions of the form
3767 //
3768 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003769 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003770 = CandidateTypes.pointer_begin();
3771 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3772 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3773
3774 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3775 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3776
3777 if (Op == OO_Plus) {
3778 // T* operator+(ptrdiff_t, T*);
3779 ParamTypes[0] = ParamTypes[1];
3780 ParamTypes[1] = *Ptr;
3781 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3782 } else {
3783 // ptrdiff_t operator-(T, T);
3784 ParamTypes[1] = *Ptr;
3785 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3786 Args, 2, CandidateSet);
3787 }
3788 }
3789 }
3790 // Fall through
3791
Douglas Gregora11693b2008-11-12 17:17:38 +00003792 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003793 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003794 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003795 // C++ [over.built]p12:
3796 //
3797 // For every pair of promoted arithmetic types L and R, there
3798 // exist candidate operator functions of the form
3799 //
3800 // LR operator*(L, R);
3801 // LR operator/(L, R);
3802 // LR operator+(L, R);
3803 // LR operator-(L, R);
3804 // bool operator<(L, R);
3805 // bool operator>(L, R);
3806 // bool operator<=(L, R);
3807 // bool operator>=(L, R);
3808 // bool operator==(L, R);
3809 // bool operator!=(L, R);
3810 //
3811 // where LR is the result of the usual arithmetic conversions
3812 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003813 //
3814 // C++ [over.built]p24:
3815 //
3816 // For every pair of promoted arithmetic types L and R, there exist
3817 // candidate operator functions of the form
3818 //
3819 // LR operator?(bool, L, R);
3820 //
3821 // where LR is the result of the usual arithmetic conversions
3822 // between types L and R.
3823 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003824 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003825 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003826 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003827 Right < LastPromotedArithmeticType; ++Right) {
3828 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003829 QualType Result
3830 = isComparison
3831 ? Context.BoolTy
3832 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003833 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3834 }
3835 }
3836 break;
3837
3838 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003839 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003840 case OO_Caret:
3841 case OO_Pipe:
3842 case OO_LessLess:
3843 case OO_GreaterGreater:
3844 // C++ [over.built]p17:
3845 //
3846 // For every pair of promoted integral types L and R, there
3847 // exist candidate operator functions of the form
3848 //
3849 // LR operator%(L, R);
3850 // LR operator&(L, R);
3851 // LR operator^(L, R);
3852 // LR operator|(L, R);
3853 // L operator<<(L, R);
3854 // L operator>>(L, R);
3855 //
3856 // where LR is the result of the usual arithmetic conversions
3857 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003858 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003859 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003860 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003861 Right < LastPromotedIntegralType; ++Right) {
3862 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3863 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3864 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003865 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003866 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3867 }
3868 }
3869 break;
3870
3871 case OO_Equal:
3872 // C++ [over.built]p20:
3873 //
3874 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003875 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003876 // empty, there exist candidate operator functions of the form
3877 //
3878 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003879 for (BuiltinCandidateTypeSet::iterator
3880 Enum = CandidateTypes.enumeration_begin(),
3881 EnumEnd = CandidateTypes.enumeration_end();
3882 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003883 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003884 CandidateSet);
3885 for (BuiltinCandidateTypeSet::iterator
3886 MemPtr = CandidateTypes.member_pointer_begin(),
3887 MemPtrEnd = CandidateTypes.member_pointer_end();
3888 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003889 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003890 CandidateSet);
3891 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003892
3893 case OO_PlusEqual:
3894 case OO_MinusEqual:
3895 // C++ [over.built]p19:
3896 //
3897 // For every pair (T, VQ), where T is any type and VQ is either
3898 // volatile or empty, there exist candidate operator functions
3899 // of the form
3900 //
3901 // T*VQ& operator=(T*VQ&, T*);
3902 //
3903 // C++ [over.built]p21:
3904 //
3905 // For every pair (T, VQ), where T is a cv-qualified or
3906 // cv-unqualified object type and VQ is either volatile or
3907 // empty, there exist candidate operator functions of the form
3908 //
3909 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3910 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3911 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3912 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3913 QualType ParamTypes[2];
3914 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3915
3916 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003917 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003918 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3919 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003920
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003921 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3922 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003923 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003924 ParamTypes[0]
3925 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003926 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3927 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003928 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003929 }
3930 // Fall through.
3931
3932 case OO_StarEqual:
3933 case OO_SlashEqual:
3934 // C++ [over.built]p18:
3935 //
3936 // For every triple (L, VQ, R), where L is an arithmetic type,
3937 // VQ is either volatile or empty, and R is a promoted
3938 // arithmetic type, there exist candidate operator functions of
3939 // the form
3940 //
3941 // VQ L& operator=(VQ L&, R);
3942 // VQ L& operator*=(VQ L&, R);
3943 // VQ L& operator/=(VQ L&, R);
3944 // VQ L& operator+=(VQ L&, R);
3945 // VQ L& operator-=(VQ L&, R);
3946 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003947 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003948 Right < LastPromotedArithmeticType; ++Right) {
3949 QualType ParamTypes[2];
3950 ParamTypes[1] = ArithmeticTypes[Right];
3951
3952 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003953 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003954 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3955 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003956
3957 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003958 if (VisibleTypeConversionsQuals.hasVolatile()) {
3959 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3960 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3961 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3962 /*IsAssigmentOperator=*/Op == OO_Equal);
3963 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003964 }
3965 }
3966 break;
3967
3968 case OO_PercentEqual:
3969 case OO_LessLessEqual:
3970 case OO_GreaterGreaterEqual:
3971 case OO_AmpEqual:
3972 case OO_CaretEqual:
3973 case OO_PipeEqual:
3974 // C++ [over.built]p22:
3975 //
3976 // For every triple (L, VQ, R), where L is an integral type, VQ
3977 // is either volatile or empty, and R is a promoted integral
3978 // type, there exist candidate operator functions of the form
3979 //
3980 // VQ L& operator%=(VQ L&, R);
3981 // VQ L& operator<<=(VQ L&, R);
3982 // VQ L& operator>>=(VQ L&, R);
3983 // VQ L& operator&=(VQ L&, R);
3984 // VQ L& operator^=(VQ L&, R);
3985 // VQ L& operator|=(VQ L&, R);
3986 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003987 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003988 Right < LastPromotedIntegralType; ++Right) {
3989 QualType ParamTypes[2];
3990 ParamTypes[1] = ArithmeticTypes[Right];
3991
3992 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003993 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003994 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003995 if (VisibleTypeConversionsQuals.hasVolatile()) {
3996 // Add this built-in operator as a candidate (VQ is 'volatile').
3997 ParamTypes[0] = ArithmeticTypes[Left];
3998 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3999 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4000 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4001 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004002 }
4003 }
4004 break;
4005
Douglas Gregord08452f2008-11-19 15:42:04 +00004006 case OO_Exclaim: {
4007 // C++ [over.operator]p23:
4008 //
4009 // There also exist candidate operator functions of the form
4010 //
Mike Stump11289f42009-09-09 15:08:12 +00004011 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004012 // bool operator&&(bool, bool); [BELOW]
4013 // bool operator||(bool, bool); [BELOW]
4014 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004015 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4016 /*IsAssignmentOperator=*/false,
4017 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004018 break;
4019 }
4020
Douglas Gregora11693b2008-11-12 17:17:38 +00004021 case OO_AmpAmp:
4022 case OO_PipePipe: {
4023 // C++ [over.operator]p23:
4024 //
4025 // There also exist candidate operator functions of the form
4026 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004027 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004028 // bool operator&&(bool, bool);
4029 // bool operator||(bool, bool);
4030 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004031 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4032 /*IsAssignmentOperator=*/false,
4033 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004034 break;
4035 }
4036
4037 case OO_Subscript:
4038 // C++ [over.built]p13:
4039 //
4040 // For every cv-qualified or cv-unqualified object type T there
4041 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004042 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004043 // T* operator+(T*, ptrdiff_t); [ABOVE]
4044 // T& operator[](T*, ptrdiff_t);
4045 // T* operator-(T*, ptrdiff_t); [ABOVE]
4046 // T* operator+(ptrdiff_t, T*); [ABOVE]
4047 // T& operator[](ptrdiff_t, T*);
4048 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4049 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4050 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004051 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004052 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004053
4054 // T& operator[](T*, ptrdiff_t)
4055 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4056
4057 // T& operator[](ptrdiff_t, T*);
4058 ParamTypes[0] = ParamTypes[1];
4059 ParamTypes[1] = *Ptr;
4060 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4061 }
4062 break;
4063
4064 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004065 // C++ [over.built]p11:
4066 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4067 // C1 is the same type as C2 or is a derived class of C2, T is an object
4068 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4069 // there exist candidate operator functions of the form
4070 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4071 // where CV12 is the union of CV1 and CV2.
4072 {
4073 for (BuiltinCandidateTypeSet::iterator Ptr =
4074 CandidateTypes.pointer_begin();
4075 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4076 QualType C1Ty = (*Ptr);
4077 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004078 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004079 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004080 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004081 if (!isa<RecordType>(C1))
4082 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004083 // heuristic to reduce number of builtin candidates in the set.
4084 // Add volatile/restrict version only if there are conversions to a
4085 // volatile/restrict type.
4086 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4087 continue;
4088 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4089 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004090 }
4091 for (BuiltinCandidateTypeSet::iterator
4092 MemPtr = CandidateTypes.member_pointer_begin(),
4093 MemPtrEnd = CandidateTypes.member_pointer_end();
4094 MemPtr != MemPtrEnd; ++MemPtr) {
4095 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4096 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004097 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004098 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4099 break;
4100 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4101 // build CV12 T&
4102 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004103 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4104 T.isVolatileQualified())
4105 continue;
4106 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4107 T.isRestrictQualified())
4108 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004109 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004110 QualType ResultTy = Context.getLValueReferenceType(T);
4111 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4112 }
4113 }
4114 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004115 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004116
4117 case OO_Conditional:
4118 // Note that we don't consider the first argument, since it has been
4119 // contextually converted to bool long ago. The candidates below are
4120 // therefore added as binary.
4121 //
4122 // C++ [over.built]p24:
4123 // For every type T, where T is a pointer or pointer-to-member type,
4124 // there exist candidate operator functions of the form
4125 //
4126 // T operator?(bool, T, T);
4127 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004128 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4129 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4130 QualType ParamTypes[2] = { *Ptr, *Ptr };
4131 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4132 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004133 for (BuiltinCandidateTypeSet::iterator Ptr =
4134 CandidateTypes.member_pointer_begin(),
4135 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4136 QualType ParamTypes[2] = { *Ptr, *Ptr };
4137 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4138 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004139 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004140 }
4141}
4142
Douglas Gregore254f902009-02-04 00:32:51 +00004143/// \brief Add function candidates found via argument-dependent lookup
4144/// to the set of overloading candidates.
4145///
4146/// This routine performs argument-dependent name lookup based on the
4147/// given function name (which may also be an operator name) and adds
4148/// all of the overload candidates found by ADL to the overload
4149/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004150void
Douglas Gregore254f902009-02-04 00:32:51 +00004151Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004152 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004153 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004154 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004155 OverloadCandidateSet& CandidateSet,
4156 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004157 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004158
John McCall91f61fc2010-01-26 06:04:06 +00004159 // FIXME: This approach for uniquing ADL results (and removing
4160 // redundant candidates from the set) relies on pointer-equality,
4161 // which means we need to key off the canonical decl. However,
4162 // always going back to the canonical decl might not get us the
4163 // right set of default arguments. What default arguments are
4164 // we supposed to consider on ADL candidates, anyway?
4165
Douglas Gregorcabea402009-09-22 15:41:20 +00004166 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004167 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004168
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004169 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004170 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4171 CandEnd = CandidateSet.end();
4172 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004173 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004174 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004175 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004176 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004177 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004178
4179 // For each of the ADL candidates we found, add it to the overload
4180 // set.
John McCall8fe68082010-01-26 07:16:45 +00004181 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00004182 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004183 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004184 continue;
4185
John McCallb89836b2010-01-26 01:37:31 +00004186 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004187 false, false, PartialOverloading);
4188 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004189 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCallb89836b2010-01-26 01:37:31 +00004190 AS_none, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004191 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004192 }
Douglas Gregore254f902009-02-04 00:32:51 +00004193}
4194
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004195/// isBetterOverloadCandidate - Determines whether the first overload
4196/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004197bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004198Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004199 const OverloadCandidate& Cand2,
4200 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004201 // Define viable functions to be better candidates than non-viable
4202 // functions.
4203 if (!Cand2.Viable)
4204 return Cand1.Viable;
4205 else if (!Cand1.Viable)
4206 return false;
4207
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004208 // C++ [over.match.best]p1:
4209 //
4210 // -- if F is a static member function, ICS1(F) is defined such
4211 // that ICS1(F) is neither better nor worse than ICS1(G) for
4212 // any function G, and, symmetrically, ICS1(G) is neither
4213 // better nor worse than ICS1(F).
4214 unsigned StartArg = 0;
4215 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4216 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004217
Douglas Gregord3cb3562009-07-07 23:38:56 +00004218 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004219 // A viable function F1 is defined to be a better function than another
4220 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004221 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004222 unsigned NumArgs = Cand1.Conversions.size();
4223 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4224 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004225 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004226 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4227 Cand2.Conversions[ArgIdx])) {
4228 case ImplicitConversionSequence::Better:
4229 // Cand1 has a better conversion sequence.
4230 HasBetterConversion = true;
4231 break;
4232
4233 case ImplicitConversionSequence::Worse:
4234 // Cand1 can't be better than Cand2.
4235 return false;
4236
4237 case ImplicitConversionSequence::Indistinguishable:
4238 // Do nothing.
4239 break;
4240 }
4241 }
4242
Mike Stump11289f42009-09-09 15:08:12 +00004243 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004244 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004245 if (HasBetterConversion)
4246 return true;
4247
Mike Stump11289f42009-09-09 15:08:12 +00004248 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004249 // specialization, or, if not that,
4250 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4251 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4252 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004253
4254 // -- F1 and F2 are function template specializations, and the function
4255 // template for F1 is more specialized than the template for F2
4256 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004257 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004258 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4259 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004260 if (FunctionTemplateDecl *BetterTemplate
4261 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4262 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004263 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004264 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4265 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004266 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004267
Douglas Gregora1f013e2008-11-07 22:36:19 +00004268 // -- the context is an initialization by user-defined conversion
4269 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4270 // from the return type of F1 to the destination type (i.e.,
4271 // the type of the entity being initialized) is a better
4272 // conversion sequence than the standard conversion sequence
4273 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004274 if (Cand1.Function && Cand2.Function &&
4275 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004276 isa<CXXConversionDecl>(Cand2.Function)) {
4277 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4278 Cand2.FinalConversion)) {
4279 case ImplicitConversionSequence::Better:
4280 // Cand1 has a better conversion sequence.
4281 return true;
4282
4283 case ImplicitConversionSequence::Worse:
4284 // Cand1 can't be better than Cand2.
4285 return false;
4286
4287 case ImplicitConversionSequence::Indistinguishable:
4288 // Do nothing
4289 break;
4290 }
4291 }
4292
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004293 return false;
4294}
4295
Mike Stump11289f42009-09-09 15:08:12 +00004296/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004297/// within an overload candidate set.
4298///
4299/// \param CandidateSet the set of candidate functions.
4300///
4301/// \param Loc the location of the function name (or operator symbol) for
4302/// which overload resolution occurs.
4303///
Mike Stump11289f42009-09-09 15:08:12 +00004304/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004305/// function, Best points to the candidate function found.
4306///
4307/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004308OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4309 SourceLocation Loc,
4310 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004311 // Find the best viable function.
4312 Best = CandidateSet.end();
4313 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4314 Cand != CandidateSet.end(); ++Cand) {
4315 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004316 if (Best == CandidateSet.end() ||
4317 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004318 Best = Cand;
4319 }
4320 }
4321
4322 // If we didn't find any viable functions, abort.
4323 if (Best == CandidateSet.end())
4324 return OR_No_Viable_Function;
4325
4326 // Make sure that this function is better than every other viable
4327 // function. If not, we have an ambiguity.
4328 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4329 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004330 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004331 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004332 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004333 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004334 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004335 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004336 }
Mike Stump11289f42009-09-09 15:08:12 +00004337
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004338 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004339 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004340 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004341 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004342 return OR_Deleted;
4343
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004344 // C++ [basic.def.odr]p2:
4345 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004346 // when referred to from a potentially-evaluated expression. [Note: this
4347 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004348 // (clause 13), user-defined conversions (12.3.2), allocation function for
4349 // placement new (5.3.4), as well as non-default initialization (8.5).
4350 if (Best->Function)
4351 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004352 return OR_Success;
4353}
4354
John McCall53262c92010-01-12 02:15:36 +00004355namespace {
4356
4357enum OverloadCandidateKind {
4358 oc_function,
4359 oc_method,
4360 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004361 oc_function_template,
4362 oc_method_template,
4363 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004364 oc_implicit_default_constructor,
4365 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004366 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004367};
4368
John McCalle1ac8d12010-01-13 00:25:19 +00004369OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4370 FunctionDecl *Fn,
4371 std::string &Description) {
4372 bool isTemplate = false;
4373
4374 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4375 isTemplate = true;
4376 Description = S.getTemplateArgumentBindingsText(
4377 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4378 }
John McCallfd0b2f82010-01-06 09:43:14 +00004379
4380 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004381 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004382 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004383
John McCall53262c92010-01-12 02:15:36 +00004384 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4385 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004386 }
4387
4388 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4389 // This actually gets spelled 'candidate function' for now, but
4390 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004391 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004392 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004393
4394 assert(Meth->isCopyAssignment()
4395 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004396 return oc_implicit_copy_assignment;
4397 }
4398
John McCalle1ac8d12010-01-13 00:25:19 +00004399 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004400}
4401
4402} // end anonymous namespace
4403
4404// Notes the location of an overload candidate.
4405void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004406 std::string FnDesc;
4407 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4408 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4409 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004410}
4411
John McCall0d1da222010-01-12 00:44:57 +00004412/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4413/// "lead" diagnostic; it will be given two arguments, the source and
4414/// target types of the conversion.
4415void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4416 SourceLocation CaretLoc,
4417 const PartialDiagnostic &PDiag) {
4418 Diag(CaretLoc, PDiag)
4419 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4420 for (AmbiguousConversionSequence::const_iterator
4421 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4422 NoteOverloadCandidate(*I);
4423 }
John McCall12f97bc2010-01-08 04:41:39 +00004424}
4425
John McCall0d1da222010-01-12 00:44:57 +00004426namespace {
4427
John McCall6a61b522010-01-13 09:16:55 +00004428void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4429 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4430 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004431 assert(Cand->Function && "for now, candidate must be a function");
4432 FunctionDecl *Fn = Cand->Function;
4433
4434 // There's a conversion slot for the object argument if this is a
4435 // non-constructor method. Note that 'I' corresponds the
4436 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004437 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004438 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004439 if (I == 0)
4440 isObjectArgument = true;
4441 else
4442 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004443 }
4444
John McCalle1ac8d12010-01-13 00:25:19 +00004445 std::string FnDesc;
4446 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4447
John McCall6a61b522010-01-13 09:16:55 +00004448 Expr *FromExpr = Conv.Bad.FromExpr;
4449 QualType FromTy = Conv.Bad.getFromType();
4450 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004451
John McCallfb7ad0f2010-02-02 02:42:52 +00004452 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004453 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004454 Expr *E = FromExpr->IgnoreParens();
4455 if (isa<UnaryOperator>(E))
4456 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004457 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004458
4459 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4460 << (unsigned) FnKind << FnDesc
4461 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4462 << ToTy << Name << I+1;
4463 return;
4464 }
4465
John McCall6d174642010-01-23 08:10:49 +00004466 // Do some hand-waving analysis to see if the non-viability is due
4467 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004468 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4469 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4470 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4471 CToTy = RT->getPointeeType();
4472 else {
4473 // TODO: detect and diagnose the full richness of const mismatches.
4474 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4475 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4476 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4477 }
4478
4479 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4480 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4481 // It is dumb that we have to do this here.
4482 while (isa<ArrayType>(CFromTy))
4483 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4484 while (isa<ArrayType>(CToTy))
4485 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4486
4487 Qualifiers FromQs = CFromTy.getQualifiers();
4488 Qualifiers ToQs = CToTy.getQualifiers();
4489
4490 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4491 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4492 << (unsigned) FnKind << FnDesc
4493 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4494 << FromTy
4495 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4496 << (unsigned) isObjectArgument << I+1;
4497 return;
4498 }
4499
4500 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4501 assert(CVR && "unexpected qualifiers mismatch");
4502
4503 if (isObjectArgument) {
4504 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4505 << (unsigned) FnKind << FnDesc
4506 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4507 << FromTy << (CVR - 1);
4508 } else {
4509 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4510 << (unsigned) FnKind << FnDesc
4511 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4512 << FromTy << (CVR - 1) << I+1;
4513 }
4514 return;
4515 }
4516
John McCall6d174642010-01-23 08:10:49 +00004517 // Diagnose references or pointers to incomplete types differently,
4518 // since it's far from impossible that the incompleteness triggered
4519 // the failure.
4520 QualType TempFromTy = FromTy.getNonReferenceType();
4521 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4522 TempFromTy = PTy->getPointeeType();
4523 if (TempFromTy->isIncompleteType()) {
4524 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4525 << (unsigned) FnKind << FnDesc
4526 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4527 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4528 return;
4529 }
4530
John McCall47000992010-01-14 03:28:57 +00004531 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004532 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4533 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004534 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004535 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004536}
4537
4538void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4539 unsigned NumFormalArgs) {
4540 // TODO: treat calls to a missing default constructor as a special case
4541
4542 FunctionDecl *Fn = Cand->Function;
4543 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4544
4545 unsigned MinParams = Fn->getMinRequiredArguments();
4546
4547 // at least / at most / exactly
4548 unsigned mode, modeCount;
4549 if (NumFormalArgs < MinParams) {
4550 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4551 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4552 mode = 0; // "at least"
4553 else
4554 mode = 2; // "exactly"
4555 modeCount = MinParams;
4556 } else {
4557 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4558 if (MinParams != FnTy->getNumArgs())
4559 mode = 1; // "at most"
4560 else
4561 mode = 2; // "exactly"
4562 modeCount = FnTy->getNumArgs();
4563 }
4564
4565 std::string Description;
4566 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4567
4568 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4569 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004570}
4571
John McCall8b9ed552010-02-01 18:53:26 +00004572/// Diagnose a failed template-argument deduction.
4573void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4574 Expr **Args, unsigned NumArgs) {
4575 FunctionDecl *Fn = Cand->Function; // pattern
4576
4577 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4578 Cand->DeductionFailure.TemplateParameter);
4579
4580 switch (Cand->DeductionFailure.Result) {
4581 case Sema::TDK_Success:
4582 llvm_unreachable("TDK_success while diagnosing bad deduction");
4583
4584 case Sema::TDK_Incomplete: {
4585 NamedDecl *ParamD;
4586 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4587 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4588 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4589 assert(ParamD && "no parameter found for incomplete deduction result");
4590 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4591 << ParamD->getDeclName();
4592 return;
4593 }
4594
4595 // TODO: diagnose these individually, then kill off
4596 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4597 case Sema::TDK_InstantiationDepth:
4598 case Sema::TDK_Inconsistent:
4599 case Sema::TDK_InconsistentQuals:
4600 case Sema::TDK_SubstitutionFailure:
4601 case Sema::TDK_NonDeducedMismatch:
4602 case Sema::TDK_TooManyArguments:
4603 case Sema::TDK_TooFewArguments:
4604 case Sema::TDK_InvalidExplicitArguments:
4605 case Sema::TDK_FailedOverloadResolution:
4606 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4607 return;
4608 }
4609}
4610
4611/// Generates a 'note' diagnostic for an overload candidate. We've
4612/// already generated a primary error at the call site.
4613///
4614/// It really does need to be a single diagnostic with its caret
4615/// pointed at the candidate declaration. Yes, this creates some
4616/// major challenges of technical writing. Yes, this makes pointing
4617/// out problems with specific arguments quite awkward. It's still
4618/// better than generating twenty screens of text for every failed
4619/// overload.
4620///
4621/// It would be great to be able to express per-candidate problems
4622/// more richly for those diagnostic clients that cared, but we'd
4623/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004624void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4625 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004626 FunctionDecl *Fn = Cand->Function;
4627
John McCall12f97bc2010-01-08 04:41:39 +00004628 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004629 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004630 std::string FnDesc;
4631 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004632
4633 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004634 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004635 return;
John McCall12f97bc2010-01-08 04:41:39 +00004636 }
4637
John McCalle1ac8d12010-01-13 00:25:19 +00004638 // We don't really have anything else to say about viable candidates.
4639 if (Cand->Viable) {
4640 S.NoteOverloadCandidate(Fn);
4641 return;
4642 }
John McCall0d1da222010-01-12 00:44:57 +00004643
John McCall6a61b522010-01-13 09:16:55 +00004644 switch (Cand->FailureKind) {
4645 case ovl_fail_too_many_arguments:
4646 case ovl_fail_too_few_arguments:
4647 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004648
John McCall6a61b522010-01-13 09:16:55 +00004649 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004650 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4651
John McCallfe796dd2010-01-23 05:17:32 +00004652 case ovl_fail_trivial_conversion:
4653 case ovl_fail_bad_final_conversion:
John McCall6a61b522010-01-13 09:16:55 +00004654 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004655
John McCall65eb8792010-02-25 01:37:24 +00004656 case ovl_fail_bad_conversion: {
4657 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4658 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00004659 if (Cand->Conversions[I].isBad())
4660 return DiagnoseBadConversion(S, Cand, I);
4661
4662 // FIXME: this currently happens when we're called from SemaInit
4663 // when user-conversion overload fails. Figure out how to handle
4664 // those conditions and diagnose them well.
4665 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004666 }
John McCall65eb8792010-02-25 01:37:24 +00004667 }
John McCalld3224162010-01-08 00:58:21 +00004668}
4669
4670void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4671 // Desugar the type of the surrogate down to a function type,
4672 // retaining as many typedefs as possible while still showing
4673 // the function type (and, therefore, its parameter types).
4674 QualType FnType = Cand->Surrogate->getConversionType();
4675 bool isLValueReference = false;
4676 bool isRValueReference = false;
4677 bool isPointer = false;
4678 if (const LValueReferenceType *FnTypeRef =
4679 FnType->getAs<LValueReferenceType>()) {
4680 FnType = FnTypeRef->getPointeeType();
4681 isLValueReference = true;
4682 } else if (const RValueReferenceType *FnTypeRef =
4683 FnType->getAs<RValueReferenceType>()) {
4684 FnType = FnTypeRef->getPointeeType();
4685 isRValueReference = true;
4686 }
4687 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4688 FnType = FnTypePtr->getPointeeType();
4689 isPointer = true;
4690 }
4691 // Desugar down to a function type.
4692 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4693 // Reconstruct the pointer/reference as appropriate.
4694 if (isPointer) FnType = S.Context.getPointerType(FnType);
4695 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4696 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4697
4698 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4699 << FnType;
4700}
4701
4702void NoteBuiltinOperatorCandidate(Sema &S,
4703 const char *Opc,
4704 SourceLocation OpLoc,
4705 OverloadCandidate *Cand) {
4706 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4707 std::string TypeStr("operator");
4708 TypeStr += Opc;
4709 TypeStr += "(";
4710 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4711 if (Cand->Conversions.size() == 1) {
4712 TypeStr += ")";
4713 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4714 } else {
4715 TypeStr += ", ";
4716 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4717 TypeStr += ")";
4718 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4719 }
4720}
4721
4722void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4723 OverloadCandidate *Cand) {
4724 unsigned NoOperands = Cand->Conversions.size();
4725 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4726 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004727 if (ICS.isBad()) break; // all meaningless after first invalid
4728 if (!ICS.isAmbiguous()) continue;
4729
4730 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4731 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004732 }
4733}
4734
John McCall3712d9e2010-01-15 23:32:50 +00004735SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4736 if (Cand->Function)
4737 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00004738 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00004739 return Cand->Surrogate->getLocation();
4740 return SourceLocation();
4741}
4742
John McCallad2587a2010-01-12 00:48:53 +00004743struct CompareOverloadCandidatesForDisplay {
4744 Sema &S;
4745 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004746
4747 bool operator()(const OverloadCandidate *L,
4748 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00004749 // Fast-path this check.
4750 if (L == R) return false;
4751
John McCall12f97bc2010-01-08 04:41:39 +00004752 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004753 if (L->Viable) {
4754 if (!R->Viable) return true;
4755
4756 // TODO: introduce a tri-valued comparison for overload
4757 // candidates. Would be more worthwhile if we had a sort
4758 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00004759 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4760 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00004761 } else if (R->Viable)
4762 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004763
John McCall3712d9e2010-01-15 23:32:50 +00004764 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004765
John McCall3712d9e2010-01-15 23:32:50 +00004766 // Criteria by which we can sort non-viable candidates:
4767 if (!L->Viable) {
4768 // 1. Arity mismatches come after other candidates.
4769 if (L->FailureKind == ovl_fail_too_many_arguments ||
4770 L->FailureKind == ovl_fail_too_few_arguments)
4771 return false;
4772 if (R->FailureKind == ovl_fail_too_many_arguments ||
4773 R->FailureKind == ovl_fail_too_few_arguments)
4774 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004775
John McCallfe796dd2010-01-23 05:17:32 +00004776 // 2. Bad conversions come first and are ordered by the number
4777 // of bad conversions and quality of good conversions.
4778 if (L->FailureKind == ovl_fail_bad_conversion) {
4779 if (R->FailureKind != ovl_fail_bad_conversion)
4780 return true;
4781
4782 // If there's any ordering between the defined conversions...
4783 // FIXME: this might not be transitive.
4784 assert(L->Conversions.size() == R->Conversions.size());
4785
4786 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00004787 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
4788 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00004789 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4790 R->Conversions[I])) {
4791 case ImplicitConversionSequence::Better:
4792 leftBetter++;
4793 break;
4794
4795 case ImplicitConversionSequence::Worse:
4796 leftBetter--;
4797 break;
4798
4799 case ImplicitConversionSequence::Indistinguishable:
4800 break;
4801 }
4802 }
4803 if (leftBetter > 0) return true;
4804 if (leftBetter < 0) return false;
4805
4806 } else if (R->FailureKind == ovl_fail_bad_conversion)
4807 return false;
4808
John McCall3712d9e2010-01-15 23:32:50 +00004809 // TODO: others?
4810 }
4811
4812 // Sort everything else by location.
4813 SourceLocation LLoc = GetLocationForCandidate(L);
4814 SourceLocation RLoc = GetLocationForCandidate(R);
4815
4816 // Put candidates without locations (e.g. builtins) at the end.
4817 if (LLoc.isInvalid()) return false;
4818 if (RLoc.isInvalid()) return true;
4819
4820 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004821 }
4822};
4823
John McCallfe796dd2010-01-23 05:17:32 +00004824/// CompleteNonViableCandidate - Normally, overload resolution only
4825/// computes up to the first
4826void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4827 Expr **Args, unsigned NumArgs) {
4828 assert(!Cand->Viable);
4829
4830 // Don't do anything on failures other than bad conversion.
4831 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4832
4833 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00004834 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00004835 unsigned ConvCount = Cand->Conversions.size();
4836 while (true) {
4837 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4838 ConvIdx++;
4839 if (Cand->Conversions[ConvIdx - 1].isBad())
4840 break;
4841 }
4842
4843 if (ConvIdx == ConvCount)
4844 return;
4845
John McCall65eb8792010-02-25 01:37:24 +00004846 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
4847 "remaining conversion is initialized?");
4848
John McCallfe796dd2010-01-23 05:17:32 +00004849 // FIXME: these should probably be preserved from the overload
4850 // operation somehow.
4851 bool SuppressUserConversions = false;
4852 bool ForceRValue = false;
4853
4854 const FunctionProtoType* Proto;
4855 unsigned ArgIdx = ConvIdx;
4856
4857 if (Cand->IsSurrogate) {
4858 QualType ConvType
4859 = Cand->Surrogate->getConversionType().getNonReferenceType();
4860 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4861 ConvType = ConvPtrType->getPointeeType();
4862 Proto = ConvType->getAs<FunctionProtoType>();
4863 ArgIdx--;
4864 } else if (Cand->Function) {
4865 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4866 if (isa<CXXMethodDecl>(Cand->Function) &&
4867 !isa<CXXConstructorDecl>(Cand->Function))
4868 ArgIdx--;
4869 } else {
4870 // Builtin binary operator with a bad first conversion.
4871 assert(ConvCount <= 3);
4872 for (; ConvIdx != ConvCount; ++ConvIdx)
4873 Cand->Conversions[ConvIdx]
4874 = S.TryCopyInitialization(Args[ConvIdx],
4875 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4876 SuppressUserConversions, ForceRValue,
4877 /*InOverloadResolution*/ true);
4878 return;
4879 }
4880
4881 // Fill in the rest of the conversions.
4882 unsigned NumArgsInProto = Proto->getNumArgs();
4883 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4884 if (ArgIdx < NumArgsInProto)
4885 Cand->Conversions[ConvIdx]
4886 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4887 SuppressUserConversions, ForceRValue,
4888 /*InOverloadResolution=*/true);
4889 else
4890 Cand->Conversions[ConvIdx].setEllipsis();
4891 }
4892}
4893
John McCalld3224162010-01-08 00:58:21 +00004894} // end anonymous namespace
4895
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004896/// PrintOverloadCandidates - When overload resolution fails, prints
4897/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004898/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004899void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004900Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004901 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004902 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004903 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004904 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004905 // Sort the candidates by viability and position. Sorting directly would
4906 // be prohibitive, so we make a set of pointers and sort those.
4907 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4908 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4909 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4910 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00004911 Cand != LastCand; ++Cand) {
4912 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00004913 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00004914 else if (OCD == OCD_AllCandidates) {
4915 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4916 Cands.push_back(Cand);
4917 }
4918 }
4919
John McCallad2587a2010-01-12 00:48:53 +00004920 std::sort(Cands.begin(), Cands.end(),
4921 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004922
John McCall0d1da222010-01-12 00:44:57 +00004923 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004924
John McCall12f97bc2010-01-08 04:41:39 +00004925 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4926 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4927 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004928
John McCalld3224162010-01-08 00:58:21 +00004929 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004930 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004931 else if (Cand->IsSurrogate)
4932 NoteSurrogateCandidate(*this, Cand);
4933
4934 // This a builtin candidate. We do not, in general, want to list
4935 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004936 else if (Cand->Viable) {
4937 // Generally we only see ambiguities including viable builtin
4938 // operators if overload resolution got screwed up by an
4939 // ambiguous user-defined conversion.
4940 //
4941 // FIXME: It's quite possible for different conversions to see
4942 // different ambiguities, though.
4943 if (!ReportedAmbiguousConversions) {
4944 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4945 ReportedAmbiguousConversions = true;
4946 }
John McCalld3224162010-01-08 00:58:21 +00004947
John McCall0d1da222010-01-12 00:44:57 +00004948 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004949 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004950 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004951 }
4952}
4953
John McCall1acbbb52010-02-02 06:20:04 +00004954static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, NamedDecl *D,
John McCall58cc69d2010-01-27 01:50:18 +00004955 AccessSpecifier AS) {
4956 if (isa<UnresolvedLookupExpr>(E))
4957 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D, AS);
4958
4959 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D, AS);
4960}
4961
Douglas Gregorcd695e52008-11-10 20:40:00 +00004962/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4963/// an overloaded function (C++ [over.over]), where @p From is an
4964/// expression with overloaded function type and @p ToType is the type
4965/// we're trying to resolve to. For example:
4966///
4967/// @code
4968/// int f(double);
4969/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004970///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004971/// int (*pfd)(double) = f; // selects f(double)
4972/// @endcode
4973///
4974/// This routine returns the resulting FunctionDecl if it could be
4975/// resolved, and NULL otherwise. When @p Complain is true, this
4976/// routine will emit diagnostics if there is an error.
4977FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004978Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004979 bool Complain) {
4980 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004981 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004982 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004983 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004984 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004985 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004986 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004987 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004988 FunctionType = MemTypePtr->getPointeeType();
4989 IsMember = true;
4990 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004991
4992 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004993 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004994 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004995 return 0;
4996
4997 // Find the actual overloaded function declaration.
John McCall1acbbb52010-02-02 06:20:04 +00004998 if (From->getType() != Context.OverloadTy)
4999 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005000
Douglas Gregorcd695e52008-11-10 20:40:00 +00005001 // C++ [over.over]p1:
5002 // [...] [Note: any redundant set of parentheses surrounding the
5003 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005004 // C++ [over.over]p1:
5005 // [...] The overloaded function name can be preceded by the &
5006 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005007 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5008 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5009 if (OvlExpr->hasExplicitTemplateArgs()) {
5010 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5011 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005012 }
5013
Douglas Gregorcd695e52008-11-10 20:40:00 +00005014 // Look through all of the overloaded functions, searching for one
5015 // whose type matches exactly.
John McCall58cc69d2010-01-27 01:50:18 +00005016 UnresolvedSet<4> Matches; // contains only FunctionDecls
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005017 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005018 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5019 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005020 // Look through any using declarations to find the underlying function.
5021 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5022
Douglas Gregorcd695e52008-11-10 20:40:00 +00005023 // C++ [over.over]p3:
5024 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005025 // targets of type "pointer-to-function" or "reference-to-function."
5026 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005027 // type "pointer-to-member-function."
5028 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005029
Mike Stump11289f42009-09-09 15:08:12 +00005030 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005031 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005032 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005033 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005034 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005035 // static when converting to member pointer.
5036 if (Method->isStatic() == IsMember)
5037 continue;
5038 } else if (IsMember)
5039 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005040
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005041 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005042 // If the name is a function template, template argument deduction is
5043 // done (14.8.2.2), and if the argument deduction succeeds, the
5044 // resulting template argument list is used to generate a single
5045 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005046 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005047 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005048 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005049 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005050 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005051 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005052 FunctionType, Specialization, Info)) {
5053 // FIXME: make a note of the failed deduction for diagnostics.
5054 (void)Result;
5055 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005056 // FIXME: If the match isn't exact, shouldn't we just drop this as
5057 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005058 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005059 == Context.getCanonicalType(Specialization->getType()));
John McCall58cc69d2010-01-27 01:50:18 +00005060 Matches.addDecl(cast<FunctionDecl>(Specialization->getCanonicalDecl()),
5061 I.getAccess());
Douglas Gregor9b146582009-07-08 20:55:45 +00005062 }
John McCalld14a8642009-11-21 08:51:07 +00005063
5064 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005065 }
Mike Stump11289f42009-09-09 15:08:12 +00005066
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005067 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005068 // Skip non-static functions when converting to pointer, and static
5069 // when converting to member pointer.
5070 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005071 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005072
5073 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005074 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005075 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005076 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005077 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005078
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005079 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005080 QualType ResultTy;
5081 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5082 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5083 ResultTy)) {
John McCall58cc69d2010-01-27 01:50:18 +00005084 Matches.addDecl(cast<FunctionDecl>(FunDecl->getCanonicalDecl()),
5085 I.getAccess());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005086 FoundNonTemplateFunction = true;
5087 }
Mike Stump11289f42009-09-09 15:08:12 +00005088 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005089 }
5090
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005091 // If there were 0 or 1 matches, we're done.
5092 if (Matches.empty())
5093 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005094 else if (Matches.size() == 1) {
John McCall58cc69d2010-01-27 01:50:18 +00005095 FunctionDecl *Result = cast<FunctionDecl>(*Matches.begin());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005096 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005097 if (Complain)
5098 CheckUnresolvedAccess(*this, OvlExpr, Result, Matches.begin().getAccess());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005099 return Result;
5100 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005101
5102 // C++ [over.over]p4:
5103 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005104 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005105 // [...] and any given function template specialization F1 is
5106 // eliminated if the set contains a second function template
5107 // specialization whose function template is more specialized
5108 // than the function template of F1 according to the partial
5109 // ordering rules of 14.5.5.2.
5110
5111 // The algorithm specified above is quadratic. We instead use a
5112 // two-pass algorithm (similar to the one used to identify the
5113 // best viable function in an overload set) that identifies the
5114 // best function template (if it exists).
John McCall58cc69d2010-01-27 01:50:18 +00005115
5116 UnresolvedSetIterator Result =
5117 getMostSpecialized(Matches.begin(), Matches.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005118 TPOC_Other, From->getLocStart(),
5119 PDiag(),
5120 PDiag(diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005121 << Matches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005122 PDiag(diag::note_ovl_candidate)
5123 << (unsigned) oc_function_template);
John McCall58cc69d2010-01-27 01:50:18 +00005124 assert(Result != Matches.end() && "no most-specialized template");
5125 MarkDeclarationReferenced(From->getLocStart(), *Result);
5126 if (Complain)
5127 CheckUnresolvedAccess(*this, OvlExpr, *Result, Result.getAccess());
5128 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005129 }
Mike Stump11289f42009-09-09 15:08:12 +00005130
Douglas Gregorfae1d712009-09-26 03:56:17 +00005131 // [...] any function template specializations in the set are
5132 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005133 for (unsigned I = 0, N = Matches.size(); I != N; ) {
5134 if (cast<FunctionDecl>(Matches[I].getDecl())->getPrimaryTemplate() == 0)
5135 ++I;
5136 else {
5137 Matches.erase(I);
5138 --N;
5139 }
5140 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005141
Mike Stump11289f42009-09-09 15:08:12 +00005142 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005143 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005144 if (Matches.size() == 1) {
5145 UnresolvedSetIterator Match = Matches.begin();
5146 MarkDeclarationReferenced(From->getLocStart(), *Match);
5147 if (Complain)
5148 CheckUnresolvedAccess(*this, OvlExpr, *Match, Match.getAccess());
5149 return cast<FunctionDecl>(*Match);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005150 }
Mike Stump11289f42009-09-09 15:08:12 +00005151
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005152 // FIXME: We should probably return the same thing that BestViableFunction
5153 // returns (even if we issue the diagnostics here).
5154 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005155 << Matches[0]->getDeclName();
5156 for (UnresolvedSetIterator I = Matches.begin(),
5157 E = Matches.end(); I != E; ++I)
5158 NoteOverloadCandidate(cast<FunctionDecl>(*I));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005159 return 0;
5160}
5161
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005162/// \brief Given an expression that refers to an overloaded function, try to
5163/// resolve that overloaded function expression down to a single function.
5164///
5165/// This routine can only resolve template-ids that refer to a single function
5166/// template, where that template-id refers to a single template whose template
5167/// arguments are either provided by the template-id or have defaults,
5168/// as described in C++0x [temp.arg.explicit]p3.
5169FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5170 // C++ [over.over]p1:
5171 // [...] [Note: any redundant set of parentheses surrounding the
5172 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005173 // C++ [over.over]p1:
5174 // [...] The overloaded function name can be preceded by the &
5175 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005176
5177 if (From->getType() != Context.OverloadTy)
5178 return 0;
5179
5180 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005181
5182 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005183 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005184 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005185
5186 TemplateArgumentListInfo ExplicitTemplateArgs;
5187 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005188
5189 // Look through all of the overloaded functions, searching for one
5190 // whose type matches exactly.
5191 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005192 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5193 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005194 // C++0x [temp.arg.explicit]p3:
5195 // [...] In contexts where deduction is done and fails, or in contexts
5196 // where deduction is not done, if a template argument list is
5197 // specified and it, along with any default template arguments,
5198 // identifies a single function template specialization, then the
5199 // template-id is an lvalue for the function template specialization.
5200 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5201
5202 // C++ [over.over]p2:
5203 // If the name is a function template, template argument deduction is
5204 // done (14.8.2.2), and if the argument deduction succeeds, the
5205 // resulting template argument list is used to generate a single
5206 // function template specialization, which is added to the set of
5207 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005208 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005209 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005210 if (TemplateDeductionResult Result
5211 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5212 Specialization, Info)) {
5213 // FIXME: make a note of the failed deduction for diagnostics.
5214 (void)Result;
5215 continue;
5216 }
5217
5218 // Multiple matches; we can't resolve to a single declaration.
5219 if (Matched)
5220 return 0;
5221
5222 Matched = Specialization;
5223 }
5224
5225 return Matched;
5226}
5227
Douglas Gregorcabea402009-09-22 15:41:20 +00005228/// \brief Add a single candidate to the overload set.
5229static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00005230 NamedDecl *Callee,
John McCallb89836b2010-01-26 01:37:31 +00005231 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00005232 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005233 Expr **Args, unsigned NumArgs,
5234 OverloadCandidateSet &CandidateSet,
5235 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005236 if (isa<UsingShadowDecl>(Callee))
5237 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5238
Douglas Gregorcabea402009-09-22 15:41:20 +00005239 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005240 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCallb89836b2010-01-26 01:37:31 +00005241 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5242 false, false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005243 return;
John McCalld14a8642009-11-21 08:51:07 +00005244 }
5245
5246 if (FunctionTemplateDecl *FuncTemplate
5247 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCallb89836b2010-01-26 01:37:31 +00005248 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005249 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005250 return;
5251 }
5252
5253 assert(false && "unhandled case in overloaded call candidate");
5254
5255 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005256}
5257
5258/// \brief Add the overload candidates named by callee and/or found by argument
5259/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005260void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005261 Expr **Args, unsigned NumArgs,
5262 OverloadCandidateSet &CandidateSet,
5263 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005264
5265#ifndef NDEBUG
5266 // Verify that ArgumentDependentLookup is consistent with the rules
5267 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005268 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005269 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5270 // and let Y be the lookup set produced by argument dependent
5271 // lookup (defined as follows). If X contains
5272 //
5273 // -- a declaration of a class member, or
5274 //
5275 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005276 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005277 //
5278 // -- a declaration that is neither a function or a function
5279 // template
5280 //
5281 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005282
John McCall57500772009-12-16 12:17:52 +00005283 if (ULE->requiresADL()) {
5284 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5285 E = ULE->decls_end(); I != E; ++I) {
5286 assert(!(*I)->getDeclContext()->isRecord());
5287 assert(isa<UsingShadowDecl>(*I) ||
5288 !(*I)->getDeclContext()->isFunctionOrMethod());
5289 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005290 }
5291 }
5292#endif
5293
John McCall57500772009-12-16 12:17:52 +00005294 // It would be nice to avoid this copy.
5295 TemplateArgumentListInfo TABuffer;
5296 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5297 if (ULE->hasExplicitTemplateArgs()) {
5298 ULE->copyTemplateArgumentsInto(TABuffer);
5299 ExplicitTemplateArgs = &TABuffer;
5300 }
5301
5302 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5303 E = ULE->decls_end(); I != E; ++I)
John McCallb89836b2010-01-26 01:37:31 +00005304 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005305 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005306 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005307
John McCall57500772009-12-16 12:17:52 +00005308 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005309 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5310 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005311 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005312 CandidateSet,
5313 PartialOverloading);
5314}
John McCalld681c392009-12-16 08:11:27 +00005315
John McCall57500772009-12-16 12:17:52 +00005316static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5317 Expr **Args, unsigned NumArgs) {
5318 Fn->Destroy(SemaRef.Context);
5319 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5320 Args[Arg]->Destroy(SemaRef.Context);
5321 return SemaRef.ExprError();
5322}
5323
John McCalld681c392009-12-16 08:11:27 +00005324/// Attempts to recover from a call where no functions were found.
5325///
5326/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005327static Sema::OwningExprResult
5328BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5329 UnresolvedLookupExpr *ULE,
5330 SourceLocation LParenLoc,
5331 Expr **Args, unsigned NumArgs,
5332 SourceLocation *CommaLocs,
5333 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005334
5335 CXXScopeSpec SS;
5336 if (ULE->getQualifier()) {
5337 SS.setScopeRep(ULE->getQualifier());
5338 SS.setRange(ULE->getQualifierRange());
5339 }
5340
John McCall57500772009-12-16 12:17:52 +00005341 TemplateArgumentListInfo TABuffer;
5342 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5343 if (ULE->hasExplicitTemplateArgs()) {
5344 ULE->copyTemplateArgumentsInto(TABuffer);
5345 ExplicitTemplateArgs = &TABuffer;
5346 }
5347
John McCalld681c392009-12-16 08:11:27 +00005348 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5349 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005350 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005351 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005352
John McCall57500772009-12-16 12:17:52 +00005353 assert(!R.empty() && "lookup results empty despite recovery");
5354
5355 // Build an implicit member call if appropriate. Just drop the
5356 // casts and such from the call, we don't really care.
5357 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5358 if ((*R.begin())->isCXXClassMember())
5359 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5360 else if (ExplicitTemplateArgs)
5361 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5362 else
5363 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5364
5365 if (NewFn.isInvalid())
5366 return Destroy(SemaRef, Fn, Args, NumArgs);
5367
5368 Fn->Destroy(SemaRef.Context);
5369
5370 // This shouldn't cause an infinite loop because we're giving it
5371 // an expression with non-empty lookup results, which should never
5372 // end up here.
5373 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5374 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5375 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005376}
Douglas Gregorcabea402009-09-22 15:41:20 +00005377
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005378/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005379/// (which eventually refers to the declaration Func) and the call
5380/// arguments Args/NumArgs, attempt to resolve the function call down
5381/// to a specific function. If overload resolution succeeds, returns
5382/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005383/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005384/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005385Sema::OwningExprResult
5386Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5387 SourceLocation LParenLoc,
5388 Expr **Args, unsigned NumArgs,
5389 SourceLocation *CommaLocs,
5390 SourceLocation RParenLoc) {
5391#ifndef NDEBUG
5392 if (ULE->requiresADL()) {
5393 // To do ADL, we must have found an unqualified name.
5394 assert(!ULE->getQualifier() && "qualified name with ADL");
5395
5396 // We don't perform ADL for implicit declarations of builtins.
5397 // Verify that this was correctly set up.
5398 FunctionDecl *F;
5399 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5400 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5401 F->getBuiltinID() && F->isImplicit())
5402 assert(0 && "performing ADL for builtin");
5403
5404 // We don't perform ADL in C.
5405 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5406 }
5407#endif
5408
John McCallbc077cf2010-02-08 23:07:23 +00005409 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005410
John McCall57500772009-12-16 12:17:52 +00005411 // Add the functions denoted by the callee to the set of candidate
5412 // functions, including those from argument-dependent lookup.
5413 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005414
5415 // If we found nothing, try to recover.
5416 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5417 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005418 if (CandidateSet.empty())
5419 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5420 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005421
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005422 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005423 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005424 case OR_Success: {
5425 FunctionDecl *FDecl = Best->Function;
John McCall58cc69d2010-01-27 01:50:18 +00005426 CheckUnresolvedLookupAccess(ULE, FDecl, Best->getAccess());
John McCall57500772009-12-16 12:17:52 +00005427 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5428 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5429 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005430
5431 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005432 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005433 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005434 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005435 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005436 break;
5437
5438 case OR_Ambiguous:
5439 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005440 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005441 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005442 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005443
5444 case OR_Deleted:
5445 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5446 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005447 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005448 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005449 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005450 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005451 }
5452
5453 // Overload resolution failed. Destroy all of the subexpressions and
5454 // return NULL.
5455 Fn->Destroy(Context);
5456 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5457 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005458 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005459}
5460
John McCall4c4c1df2010-01-26 03:27:55 +00005461static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005462 return Functions.size() > 1 ||
5463 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5464}
5465
Douglas Gregor084d8552009-03-13 23:49:33 +00005466/// \brief Create a unary operation that may resolve to an overloaded
5467/// operator.
5468///
5469/// \param OpLoc The location of the operator itself (e.g., '*').
5470///
5471/// \param OpcIn The UnaryOperator::Opcode that describes this
5472/// operator.
5473///
5474/// \param Functions The set of non-member functions that will be
5475/// considered by overload resolution. The caller needs to build this
5476/// set based on the context using, e.g.,
5477/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5478/// set should not contain any member functions; those will be added
5479/// by CreateOverloadedUnaryOp().
5480///
5481/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005482Sema::OwningExprResult
5483Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5484 const UnresolvedSetImpl &Fns,
5485 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005486 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5487 Expr *Input = (Expr *)input.get();
5488
5489 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5490 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5491 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5492
5493 Expr *Args[2] = { Input, 0 };
5494 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005495
Douglas Gregor084d8552009-03-13 23:49:33 +00005496 // For post-increment and post-decrement, add the implicit '0' as
5497 // the second argument, so that we know this is a post-increment or
5498 // post-decrement.
5499 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5500 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005501 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005502 SourceLocation());
5503 NumArgs = 2;
5504 }
5505
5506 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005507 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005508 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005509 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005510 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005511 /*ADL*/ true, IsOverloaded(Fns));
5512 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005513
Douglas Gregor084d8552009-03-13 23:49:33 +00005514 input.release();
5515 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5516 &Args[0], NumArgs,
5517 Context.DependentTy,
5518 OpLoc));
5519 }
5520
5521 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005522 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005523
5524 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005525 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005526
5527 // Add operator candidates that are member functions.
5528 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5529
John McCall4c4c1df2010-01-26 03:27:55 +00005530 // Add candidates from ADL.
5531 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005532 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005533 /*ExplicitTemplateArgs*/ 0,
5534 CandidateSet);
5535
Douglas Gregor084d8552009-03-13 23:49:33 +00005536 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005537 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005538
5539 // Perform overload resolution.
5540 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005541 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005542 case OR_Success: {
5543 // We found a built-in operator or an overloaded operator.
5544 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005545
Douglas Gregor084d8552009-03-13 23:49:33 +00005546 if (FnDecl) {
5547 // We matched an overloaded operator. Build a call to that
5548 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005549
Douglas Gregor084d8552009-03-13 23:49:33 +00005550 // Convert the arguments.
5551 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall1064d7e2010-03-16 05:22:47 +00005552 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Method, Best->getAccess());
John McCallb3a44002010-01-28 01:42:12 +00005553
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005554 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005555 return ExprError();
5556 } else {
5557 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005558 OwningExprResult InputInit
5559 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005560 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005561 SourceLocation(),
5562 move(input));
5563 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005564 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005565
Douglas Gregore6600372009-12-23 17:40:29 +00005566 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005567 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005568 }
5569
5570 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005571 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005572
Douglas Gregor084d8552009-03-13 23:49:33 +00005573 // Build the actual expression node.
5574 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5575 SourceLocation());
5576 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005577
Douglas Gregor084d8552009-03-13 23:49:33 +00005578 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005579 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005580 ExprOwningPtr<CallExpr> TheCall(this,
5581 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005582 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005583
5584 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5585 FnDecl))
5586 return ExprError();
5587
5588 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005589 } else {
5590 // We matched a built-in operator. Convert the arguments, then
5591 // break out so that we will build the appropriate built-in
5592 // operator node.
5593 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005594 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005595 return ExprError();
5596
5597 break;
5598 }
5599 }
5600
5601 case OR_No_Viable_Function:
5602 // No viable function; fall through to handling this as a
5603 // built-in operator, which will produce an error message for us.
5604 break;
5605
5606 case OR_Ambiguous:
5607 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5608 << UnaryOperator::getOpcodeStr(Opc)
5609 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005610 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005611 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005612 return ExprError();
5613
5614 case OR_Deleted:
5615 Diag(OpLoc, diag::err_ovl_deleted_oper)
5616 << Best->Function->isDeleted()
5617 << UnaryOperator::getOpcodeStr(Opc)
5618 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005619 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005620 return ExprError();
5621 }
5622
5623 // Either we found no viable overloaded operator or we matched a
5624 // built-in operator. In either case, fall through to trying to
5625 // build a built-in operation.
5626 input.release();
5627 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5628}
5629
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005630/// \brief Create a binary operation that may resolve to an overloaded
5631/// operator.
5632///
5633/// \param OpLoc The location of the operator itself (e.g., '+').
5634///
5635/// \param OpcIn The BinaryOperator::Opcode that describes this
5636/// operator.
5637///
5638/// \param Functions The set of non-member functions that will be
5639/// considered by overload resolution. The caller needs to build this
5640/// set based on the context using, e.g.,
5641/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5642/// set should not contain any member functions; those will be added
5643/// by CreateOverloadedBinOp().
5644///
5645/// \param LHS Left-hand argument.
5646/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005647Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005648Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005649 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005650 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005651 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005652 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005653 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005654
5655 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5656 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5657 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5658
5659 // If either side is type-dependent, create an appropriate dependent
5660 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005661 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00005662 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005663 // If there are no functions to store, just build a dependent
5664 // BinaryOperator or CompoundAssignment.
5665 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5666 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5667 Context.DependentTy, OpLoc));
5668
5669 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5670 Context.DependentTy,
5671 Context.DependentTy,
5672 Context.DependentTy,
5673 OpLoc));
5674 }
John McCall4c4c1df2010-01-26 03:27:55 +00005675
5676 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00005677 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005678 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005679 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005680 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005681 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00005682
John McCall4c4c1df2010-01-26 03:27:55 +00005683 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005684 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005685 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005686 Context.DependentTy,
5687 OpLoc));
5688 }
5689
5690 // If this is the .* operator, which is not overloadable, just
5691 // create a built-in binary operator.
5692 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005693 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005694
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005695 // If this is the assignment operator, we only perform overload resolution
5696 // if the left-hand side is a class or enumeration type. This is actually
5697 // a hack. The standard requires that we do overload resolution between the
5698 // various built-in candidates, but as DR507 points out, this can lead to
5699 // problems. So we do it this way, which pretty much follows what GCC does.
5700 // Note that we go the traditional code path for compound assignment forms.
5701 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005702 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005703
Douglas Gregor084d8552009-03-13 23:49:33 +00005704 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005705 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005706
5707 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005708 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005709
5710 // Add operator candidates that are member functions.
5711 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5712
John McCall4c4c1df2010-01-26 03:27:55 +00005713 // Add candidates from ADL.
5714 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5715 Args, 2,
5716 /*ExplicitTemplateArgs*/ 0,
5717 CandidateSet);
5718
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005719 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005720 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005721
5722 // Perform overload resolution.
5723 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005724 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005725 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005726 // We found a built-in operator or an overloaded operator.
5727 FunctionDecl *FnDecl = Best->Function;
5728
5729 if (FnDecl) {
5730 // We matched an overloaded operator. Build a call to that
5731 // operator.
5732
5733 // Convert the arguments.
5734 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005735 // Best->Access is only meaningful for class members.
John McCall1064d7e2010-03-16 05:22:47 +00005736 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Method,
5737 Best->getAccess());
John McCallb3a44002010-01-28 01:42:12 +00005738
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005739 OwningExprResult Arg1
5740 = PerformCopyInitialization(
5741 InitializedEntity::InitializeParameter(
5742 FnDecl->getParamDecl(0)),
5743 SourceLocation(),
5744 Owned(Args[1]));
5745 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005746 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005747
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005748 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5749 Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005750 return ExprError();
5751
5752 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005753 } else {
5754 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005755 OwningExprResult Arg0
5756 = PerformCopyInitialization(
5757 InitializedEntity::InitializeParameter(
5758 FnDecl->getParamDecl(0)),
5759 SourceLocation(),
5760 Owned(Args[0]));
5761 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005762 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005763
5764 OwningExprResult Arg1
5765 = PerformCopyInitialization(
5766 InitializedEntity::InitializeParameter(
5767 FnDecl->getParamDecl(1)),
5768 SourceLocation(),
5769 Owned(Args[1]));
5770 if (Arg1.isInvalid())
5771 return ExprError();
5772 Args[0] = LHS = Arg0.takeAs<Expr>();
5773 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005774 }
5775
5776 // Determine the result type
5777 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005778 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005779 ResultTy = ResultTy.getNonReferenceType();
5780
5781 // Build the actual expression node.
5782 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005783 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005784 UsualUnaryConversions(FnExpr);
5785
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005786 ExprOwningPtr<CXXOperatorCallExpr>
5787 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5788 Args, 2, ResultTy,
5789 OpLoc));
5790
5791 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5792 FnDecl))
5793 return ExprError();
5794
5795 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005796 } else {
5797 // We matched a built-in operator. Convert the arguments, then
5798 // break out so that we will build the appropriate built-in
5799 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005800 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005801 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005802 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005803 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005804 return ExprError();
5805
5806 break;
5807 }
5808 }
5809
Douglas Gregor66950a32009-09-30 21:46:01 +00005810 case OR_No_Viable_Function: {
5811 // C++ [over.match.oper]p9:
5812 // If the operator is the operator , [...] and there are no
5813 // viable functions, then the operator is assumed to be the
5814 // built-in operator and interpreted according to clause 5.
5815 if (Opc == BinaryOperator::Comma)
5816 break;
5817
Sebastian Redl027de2a2009-05-21 11:50:50 +00005818 // For class as left operand for assignment or compound assigment operator
5819 // do not fall through to handling in built-in, but report that no overloaded
5820 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005821 OwningExprResult Result = ExprError();
5822 if (Args[0]->getType()->isRecordType() &&
5823 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005824 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5825 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005826 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005827 } else {
5828 // No viable function; try to create a built-in operation, which will
5829 // produce an error. Then, show the non-viable candidates.
5830 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005831 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005832 assert(Result.isInvalid() &&
5833 "C++ binary operator overloading is missing candidates!");
5834 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005835 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005836 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005837 return move(Result);
5838 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005839
5840 case OR_Ambiguous:
5841 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5842 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005843 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005844 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005845 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005846 return ExprError();
5847
5848 case OR_Deleted:
5849 Diag(OpLoc, diag::err_ovl_deleted_oper)
5850 << Best->Function->isDeleted()
5851 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005852 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005853 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005854 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005855 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005856
Douglas Gregor66950a32009-09-30 21:46:01 +00005857 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005858 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005859}
5860
Sebastian Redladba46e2009-10-29 20:17:01 +00005861Action::OwningExprResult
5862Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5863 SourceLocation RLoc,
5864 ExprArg Base, ExprArg Idx) {
5865 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5866 static_cast<Expr*>(Idx.get()) };
5867 DeclarationName OpName =
5868 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5869
5870 // If either side is type-dependent, create an appropriate dependent
5871 // expression.
5872 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5873
John McCall58cc69d2010-01-27 01:50:18 +00005874 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005875 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005876 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005877 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005878 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005879 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005880
5881 Base.release();
5882 Idx.release();
5883 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5884 Args, 2,
5885 Context.DependentTy,
5886 RLoc));
5887 }
5888
5889 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005890 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005891
5892 // Subscript can only be overloaded as a member function.
5893
5894 // Add operator candidates that are member functions.
5895 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5896
5897 // Add builtin operator candidates.
5898 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5899
5900 // Perform overload resolution.
5901 OverloadCandidateSet::iterator Best;
5902 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5903 case OR_Success: {
5904 // We found a built-in operator or an overloaded operator.
5905 FunctionDecl *FnDecl = Best->Function;
5906
5907 if (FnDecl) {
5908 // We matched an overloaded operator. Build a call to that
5909 // operator.
5910
John McCall1064d7e2010-03-16 05:22:47 +00005911 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], FnDecl,
5912 Best->getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005913
Sebastian Redladba46e2009-10-29 20:17:01 +00005914 // Convert the arguments.
5915 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005916 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5917 Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00005918 return ExprError();
5919
Anders Carlssona68e51e2010-01-29 18:37:50 +00005920 // Convert the arguments.
5921 OwningExprResult InputInit
5922 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5923 FnDecl->getParamDecl(0)),
5924 SourceLocation(),
5925 Owned(Args[1]));
5926 if (InputInit.isInvalid())
5927 return ExprError();
5928
5929 Args[1] = InputInit.takeAs<Expr>();
5930
Sebastian Redladba46e2009-10-29 20:17:01 +00005931 // Determine the result type
5932 QualType ResultTy
5933 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5934 ResultTy = ResultTy.getNonReferenceType();
5935
5936 // Build the actual expression node.
5937 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5938 LLoc);
5939 UsualUnaryConversions(FnExpr);
5940
5941 Base.release();
5942 Idx.release();
5943 ExprOwningPtr<CXXOperatorCallExpr>
5944 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5945 FnExpr, Args, 2,
5946 ResultTy, RLoc));
5947
5948 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5949 FnDecl))
5950 return ExprError();
5951
5952 return MaybeBindToTemporary(TheCall.release());
5953 } else {
5954 // We matched a built-in operator. Convert the arguments, then
5955 // break out so that we will build the appropriate built-in
5956 // operator node.
5957 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005958 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005959 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005960 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005961 return ExprError();
5962
5963 break;
5964 }
5965 }
5966
5967 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005968 if (CandidateSet.empty())
5969 Diag(LLoc, diag::err_ovl_no_oper)
5970 << Args[0]->getType() << /*subscript*/ 0
5971 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5972 else
5973 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5974 << Args[0]->getType()
5975 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005976 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005977 "[]", LLoc);
5978 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005979 }
5980
5981 case OR_Ambiguous:
5982 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5983 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005984 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005985 "[]", LLoc);
5986 return ExprError();
5987
5988 case OR_Deleted:
5989 Diag(LLoc, diag::err_ovl_deleted_oper)
5990 << Best->Function->isDeleted() << "[]"
5991 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005992 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005993 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005994 return ExprError();
5995 }
5996
5997 // We matched a built-in operator; build it.
5998 Base.release();
5999 Idx.release();
6000 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6001 Owned(Args[1]), RLoc);
6002}
6003
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006004/// BuildCallToMemberFunction - Build a call to a member
6005/// function. MemExpr is the expression that refers to the member
6006/// function (and includes the object parameter), Args/NumArgs are the
6007/// arguments to the function call (not including the object
6008/// parameter). The caller needs to validate that the member
6009/// expression refers to a member function or an overloaded member
6010/// function.
John McCall2d74de92009-12-01 22:10:20 +00006011Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006012Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6013 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006014 unsigned NumArgs, SourceLocation *CommaLocs,
6015 SourceLocation RParenLoc) {
6016 // Dig out the member expression. This holds both the object
6017 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006018 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6019
John McCall10eae182009-11-30 22:42:35 +00006020 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006021 CXXMethodDecl *Method = 0;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006022 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006023 if (isa<MemberExpr>(NakedMemExpr)) {
6024 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006025 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006026 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006027 } else {
6028 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006029 Qualifier = UnresExpr->getQualifier();
6030
John McCall6e9f8f62009-12-03 04:06:58 +00006031 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006032
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006033 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006034 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006035
John McCall2d74de92009-12-01 22:10:20 +00006036 // FIXME: avoid copy.
6037 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6038 if (UnresExpr->hasExplicitTemplateArgs()) {
6039 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6040 TemplateArgs = &TemplateArgsBuffer;
6041 }
6042
John McCall10eae182009-11-30 22:42:35 +00006043 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6044 E = UnresExpr->decls_end(); I != E; ++I) {
6045
John McCall6e9f8f62009-12-03 04:06:58 +00006046 NamedDecl *Func = *I;
6047 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6048 if (isa<UsingShadowDecl>(Func))
6049 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6050
John McCall10eae182009-11-30 22:42:35 +00006051 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006052 // If explicit template arguments were provided, we can't call a
6053 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006054 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006055 continue;
6056
John McCallb89836b2010-01-26 01:37:31 +00006057 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
6058 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006059 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006060 } else {
John McCall10eae182009-11-30 22:42:35 +00006061 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCallb89836b2010-01-26 01:37:31 +00006062 I.getAccess(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006063 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006064 CandidateSet,
6065 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006066 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006067 }
Mike Stump11289f42009-09-09 15:08:12 +00006068
John McCall10eae182009-11-30 22:42:35 +00006069 DeclarationName DeclName = UnresExpr->getMemberName();
6070
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006071 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006072 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006073 case OR_Success:
6074 Method = cast<CXXMethodDecl>(Best->Function);
John McCall58cc69d2010-01-27 01:50:18 +00006075 CheckUnresolvedMemberAccess(UnresExpr, Method, Best->getAccess());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006076 break;
6077
6078 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006079 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006080 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006081 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006082 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006083 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006084 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006085
6086 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006087 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006088 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006089 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006090 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006091 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006092
6093 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006094 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006095 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006096 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006097 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006098 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006099 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006100 }
6101
Douglas Gregor51c538b2009-11-20 19:42:02 +00006102 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00006103
John McCall2d74de92009-12-01 22:10:20 +00006104 // If overload resolution picked a static member, build a
6105 // non-member call based on that function.
6106 if (Method->isStatic()) {
6107 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6108 Args, NumArgs, RParenLoc);
6109 }
6110
John McCall10eae182009-11-30 22:42:35 +00006111 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006112 }
6113
6114 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006115 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006116 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006117 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006118 Method->getResultType().getNonReferenceType(),
6119 RParenLoc));
6120
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006121 // Check for a valid return type.
6122 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6123 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006124 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006125
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006126 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00006127 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006128 if (!Method->isStatic() &&
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006129 PerformObjectArgumentInitialization(ObjectArg, Qualifier, Method))
John McCall2d74de92009-12-01 22:10:20 +00006130 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006131 MemExpr->setBase(ObjectArg);
6132
6133 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006134 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006135 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006136 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006137 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006138
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006139 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006140 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006141
John McCall2d74de92009-12-01 22:10:20 +00006142 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006143}
6144
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006145/// BuildCallToObjectOfClassType - Build a call to an object of class
6146/// type (C++ [over.call.object]), which can end up invoking an
6147/// overloaded function call operator (@c operator()) or performing a
6148/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006149Sema::ExprResult
6150Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006151 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006152 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006153 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006154 SourceLocation RParenLoc) {
6155 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006156 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006157
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006158 // C++ [over.call.object]p1:
6159 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006160 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006161 // candidate functions includes at least the function call
6162 // operators of T. The function call operators of T are obtained by
6163 // ordinary lookup of the name operator() in the context of
6164 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006165 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006166 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006167
6168 if (RequireCompleteType(LParenLoc, Object->getType(),
6169 PartialDiagnostic(diag::err_incomplete_object_call)
6170 << Object->getSourceRange()))
6171 return true;
6172
John McCall27b18f82009-11-17 02:14:36 +00006173 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6174 LookupQualifiedName(R, Record->getDecl());
6175 R.suppressDiagnostics();
6176
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006177 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006178 Oper != OperEnd; ++Oper) {
John McCallb89836b2010-01-26 01:37:31 +00006179 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6180 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006181 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006182 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006183
Douglas Gregorab7897a2008-11-19 22:57:39 +00006184 // C++ [over.call.object]p2:
6185 // In addition, for each conversion function declared in T of the
6186 // form
6187 //
6188 // operator conversion-type-id () cv-qualifier;
6189 //
6190 // where cv-qualifier is the same cv-qualification as, or a
6191 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006192 // denotes the type "pointer to function of (P1,...,Pn) returning
6193 // R", or the type "reference to pointer to function of
6194 // (P1,...,Pn) returning R", or the type "reference to function
6195 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006196 // is also considered as a candidate function. Similarly,
6197 // surrogate call functions are added to the set of candidate
6198 // functions for each conversion function declared in an
6199 // accessible base class provided the function is not hidden
6200 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006201 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006202 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006203 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006204 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006205 NamedDecl *D = *I;
6206 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6207 if (isa<UsingShadowDecl>(D))
6208 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6209
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006210 // Skip over templated conversion functions; they aren't
6211 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006212 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006213 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006214
John McCall6e9f8f62009-12-03 04:06:58 +00006215 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006216
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006217 // Strip the reference type (if any) and then the pointer type (if
6218 // any) to get down to what might be a function type.
6219 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6220 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6221 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006222
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006223 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCallb89836b2010-01-26 01:37:31 +00006224 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006225 Object->getType(), Args, NumArgs,
6226 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006227 }
Mike Stump11289f42009-09-09 15:08:12 +00006228
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006229 // Perform overload resolution.
6230 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006231 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006232 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006233 // Overload resolution succeeded; we'll build the appropriate call
6234 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006235 break;
6236
6237 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006238 if (CandidateSet.empty())
6239 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6240 << Object->getType() << /*call*/ 1
6241 << Object->getSourceRange();
6242 else
6243 Diag(Object->getSourceRange().getBegin(),
6244 diag::err_ovl_no_viable_object_call)
6245 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006246 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006247 break;
6248
6249 case OR_Ambiguous:
6250 Diag(Object->getSourceRange().getBegin(),
6251 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006252 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006253 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006254 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006255
6256 case OR_Deleted:
6257 Diag(Object->getSourceRange().getBegin(),
6258 diag::err_ovl_deleted_object_call)
6259 << Best->Function->isDeleted()
6260 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006261 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006262 break;
Mike Stump11289f42009-09-09 15:08:12 +00006263 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006264
Douglas Gregorab7897a2008-11-19 22:57:39 +00006265 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006266 // We had an error; delete all of the subexpressions and return
6267 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006268 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006269 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006270 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006271 return true;
6272 }
6273
Douglas Gregorab7897a2008-11-19 22:57:39 +00006274 if (Best->Function == 0) {
6275 // Since there is no function declaration, this is one of the
6276 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006277 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006278 = cast<CXXConversionDecl>(
6279 Best->Conversions[0].UserDefined.ConversionFunction);
6280
John McCall1064d7e2010-03-16 05:22:47 +00006281 CheckMemberOperatorAccess(LParenLoc, Object, 0, Conv, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006282
Douglas Gregorab7897a2008-11-19 22:57:39 +00006283 // We selected one of the surrogate functions that converts the
6284 // object parameter to a function pointer. Perform the conversion
6285 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006286
6287 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006288 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006289 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006290
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006291 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006292 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6293 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006294 }
6295
John McCall1064d7e2010-03-16 05:22:47 +00006296 CheckMemberOperatorAccess(LParenLoc, Object, 0,
John McCall2cb94162010-01-28 07:38:46 +00006297 Best->Function, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006298
Douglas Gregorab7897a2008-11-19 22:57:39 +00006299 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6300 // that calls this method, using Object for the implicit object
6301 // parameter and passing along the remaining arguments.
6302 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006303 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006304
6305 unsigned NumArgsInProto = Proto->getNumArgs();
6306 unsigned NumArgsToCheck = NumArgs;
6307
6308 // Build the full argument list for the method call (the
6309 // implicit object parameter is placed at the beginning of the
6310 // list).
6311 Expr **MethodArgs;
6312 if (NumArgs < NumArgsInProto) {
6313 NumArgsToCheck = NumArgsInProto;
6314 MethodArgs = new Expr*[NumArgsInProto + 1];
6315 } else {
6316 MethodArgs = new Expr*[NumArgs + 1];
6317 }
6318 MethodArgs[0] = Object;
6319 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6320 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006321
6322 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006323 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006324 UsualUnaryConversions(NewFn);
6325
6326 // Once we've built TheCall, all of the expressions are properly
6327 // owned.
6328 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006329 ExprOwningPtr<CXXOperatorCallExpr>
6330 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006331 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006332 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006333 delete [] MethodArgs;
6334
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006335 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6336 Method))
6337 return true;
6338
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006339 // We may have default arguments. If so, we need to allocate more
6340 // slots in the call for them.
6341 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006342 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006343 else if (NumArgs > NumArgsInProto)
6344 NumArgsToCheck = NumArgsInProto;
6345
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006346 bool IsError = false;
6347
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006348 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006349 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
6350 Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006351 TheCall->setArg(0, Object);
6352
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006353
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006354 // Check the argument types.
6355 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006356 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006357 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006358 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006359
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006360 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006361
6362 OwningExprResult InputInit
6363 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6364 Method->getParamDecl(i)),
6365 SourceLocation(), Owned(Arg));
6366
6367 IsError |= InputInit.isInvalid();
6368 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006369 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006370 OwningExprResult DefArg
6371 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6372 if (DefArg.isInvalid()) {
6373 IsError = true;
6374 break;
6375 }
6376
6377 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006378 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006379
6380 TheCall->setArg(i + 1, Arg);
6381 }
6382
6383 // If this is a variadic call, handle args passed through "...".
6384 if (Proto->isVariadic()) {
6385 // Promote the arguments (C99 6.5.2.2p7).
6386 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6387 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006388 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006389 TheCall->setArg(i + 1, Arg);
6390 }
6391 }
6392
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006393 if (IsError) return true;
6394
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006395 if (CheckFunctionCall(Method, TheCall.get()))
6396 return true;
6397
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006398 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006399}
6400
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006401/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006402/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006403/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006404Sema::OwningExprResult
6405Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6406 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006407 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006408
John McCallbc077cf2010-02-08 23:07:23 +00006409 SourceLocation Loc = Base->getExprLoc();
6410
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006411 // C++ [over.ref]p1:
6412 //
6413 // [...] An expression x->m is interpreted as (x.operator->())->m
6414 // for a class object x of type T if T::operator->() exists and if
6415 // the operator is selected as the best match function by the
6416 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006417 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006418 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006419 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006420
John McCallbc077cf2010-02-08 23:07:23 +00006421 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006422 PDiag(diag::err_typecheck_incomplete_tag)
6423 << Base->getSourceRange()))
6424 return ExprError();
6425
John McCall27b18f82009-11-17 02:14:36 +00006426 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6427 LookupQualifiedName(R, BaseRecord->getDecl());
6428 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006429
6430 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006431 Oper != OperEnd; ++Oper) {
6432 NamedDecl *D = *Oper;
6433 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6434 if (isa<UsingShadowDecl>(D))
6435 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6436
John McCallb89836b2010-01-26 01:37:31 +00006437 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00006438 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006439 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006440 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006441
6442 // Perform overload resolution.
6443 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006444 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006445 case OR_Success:
6446 // Overload resolution succeeded; we'll build the call below.
6447 break;
6448
6449 case OR_No_Viable_Function:
6450 if (CandidateSet.empty())
6451 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006452 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006453 else
6454 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006455 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006456 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006457 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006458
6459 case OR_Ambiguous:
6460 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006461 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006462 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006463 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006464
6465 case OR_Deleted:
6466 Diag(OpLoc, diag::err_ovl_deleted_oper)
6467 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006468 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006469 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006470 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006471 }
6472
6473 // Convert the object parameter.
6474 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006475 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006476 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006477
6478 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006479 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006480
6481 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006482 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6483 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006484 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006485
6486 QualType ResultTy = Method->getResultType().getNonReferenceType();
6487 ExprOwningPtr<CXXOperatorCallExpr>
6488 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6489 &Base, 1, ResultTy, OpLoc));
6490
6491 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6492 Method))
6493 return ExprError();
6494 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006495}
6496
Douglas Gregorcd695e52008-11-10 20:40:00 +00006497/// FixOverloadedFunctionReference - E is an expression that refers to
6498/// a C++ overloaded function (possibly with some parentheses and
6499/// perhaps a '&' around it). We have resolved the overloaded function
6500/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006501/// refer (possibly indirectly) to Fn. Returns the new expr.
6502Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006503 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006504 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6505 if (SubExpr == PE->getSubExpr())
6506 return PE->Retain();
6507
6508 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6509 }
6510
6511 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6512 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006513 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006514 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006515 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006516 if (SubExpr == ICE->getSubExpr())
6517 return ICE->Retain();
6518
6519 return new (Context) ImplicitCastExpr(ICE->getType(),
6520 ICE->getCastKind(),
6521 SubExpr,
6522 ICE->isLvalueCast());
6523 }
6524
6525 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006526 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006527 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006528 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6529 if (Method->isStatic()) {
6530 // Do nothing: static member functions aren't any different
6531 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006532 } else {
John McCalle66edc12009-11-24 19:00:30 +00006533 // Fix the sub expression, which really has to be an
6534 // UnresolvedLookupExpr holding an overloaded member function
6535 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006536 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6537 if (SubExpr == UnOp->getSubExpr())
6538 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006539
John McCalld14a8642009-11-21 08:51:07 +00006540 assert(isa<DeclRefExpr>(SubExpr)
6541 && "fixed to something other than a decl ref");
6542 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6543 && "fixed to a member ref with no nested name qualifier");
6544
6545 // We have taken the address of a pointer to member
6546 // function. Perform the computation here so that we get the
6547 // appropriate pointer to member type.
6548 QualType ClassType
6549 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6550 QualType MemPtrType
6551 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6552
6553 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6554 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006555 }
6556 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006557 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6558 if (SubExpr == UnOp->getSubExpr())
6559 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006560
Douglas Gregor51c538b2009-11-20 19:42:02 +00006561 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6562 Context.getPointerType(SubExpr->getType()),
6563 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006564 }
John McCalld14a8642009-11-21 08:51:07 +00006565
6566 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006567 // FIXME: avoid copy.
6568 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006569 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006570 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6571 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006572 }
6573
John McCalld14a8642009-11-21 08:51:07 +00006574 return DeclRefExpr::Create(Context,
6575 ULE->getQualifier(),
6576 ULE->getQualifierRange(),
6577 Fn,
6578 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006579 Fn->getType(),
6580 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006581 }
6582
John McCall10eae182009-11-30 22:42:35 +00006583 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006584 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006585 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6586 if (MemExpr->hasExplicitTemplateArgs()) {
6587 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6588 TemplateArgs = &TemplateArgsBuffer;
6589 }
John McCall6b51f282009-11-23 01:53:49 +00006590
John McCall2d74de92009-12-01 22:10:20 +00006591 Expr *Base;
6592
6593 // If we're filling in
6594 if (MemExpr->isImplicitAccess()) {
6595 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6596 return DeclRefExpr::Create(Context,
6597 MemExpr->getQualifier(),
6598 MemExpr->getQualifierRange(),
6599 Fn,
6600 MemExpr->getMemberLoc(),
6601 Fn->getType(),
6602 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006603 } else {
6604 SourceLocation Loc = MemExpr->getMemberLoc();
6605 if (MemExpr->getQualifier())
6606 Loc = MemExpr->getQualifierRange().getBegin();
6607 Base = new (Context) CXXThisExpr(Loc,
6608 MemExpr->getBaseType(),
6609 /*isImplicit=*/true);
6610 }
John McCall2d74de92009-12-01 22:10:20 +00006611 } else
6612 Base = MemExpr->getBase()->Retain();
6613
6614 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006615 MemExpr->isArrow(),
6616 MemExpr->getQualifier(),
6617 MemExpr->getQualifierRange(),
6618 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006619 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006620 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006621 Fn->getType());
6622 }
6623
Douglas Gregor51c538b2009-11-20 19:42:02 +00006624 assert(false && "Invalid reference to overloaded function");
6625 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006626}
6627
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006628Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6629 FunctionDecl *Fn) {
6630 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6631}
6632
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006633} // end namespace clang