blob: 7208b90939a787b954bb3b518c5b52954afce094 [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;
121 Deprecated = false;
122 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 Gregor26bee0b2008-10-31 16:23:19 +0000552 SCS.Deprecated = 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 Gregor26bee0b2008-10-31 16:23:19 +0000595 SCS.Deprecated = 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)) {
1138 ConvertedType = ToType;
1139 return true;
1140 }
1141
1142 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1143 // Okay: this is some kind of implicit downcast of Objective-C
1144 // interfaces, which is permitted. However, we're going to
1145 // complain about it.
1146 IncompatibleObjC = true;
1147 ConvertedType = FromType;
1148 return true;
1149 }
Mike Stump11289f42009-09-09 15:08:12 +00001150 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001151 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001152 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001153 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001154 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001155 else if (const BlockPointerType *ToBlockPtr =
1156 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001157 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001158 // to a block pointer type.
1159 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1160 ConvertedType = ToType;
1161 return true;
1162 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001163 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001164 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001165 else if (FromType->getAs<BlockPointerType>() &&
1166 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1167 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001168 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001169 ConvertedType = ToType;
1170 return true;
1171 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001172 else
Douglas Gregora119f102008-12-19 19:13:09 +00001173 return false;
1174
Douglas Gregor033f56d2008-12-23 00:53:59 +00001175 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001176 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001177 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001178 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001179 FromPointeeType = FromBlockPtr->getPointeeType();
1180 else
Douglas Gregora119f102008-12-19 19:13:09 +00001181 return false;
1182
Douglas Gregora119f102008-12-19 19:13:09 +00001183 // If we have pointers to pointers, recursively check whether this
1184 // is an Objective-C conversion.
1185 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1186 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1187 IncompatibleObjC)) {
1188 // We always complain about this conversion.
1189 IncompatibleObjC = true;
1190 ConvertedType = ToType;
1191 return true;
1192 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001193 // Allow conversion of pointee being objective-c pointer to another one;
1194 // as in I* to id.
1195 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1196 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1197 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1198 IncompatibleObjC)) {
1199 ConvertedType = ToType;
1200 return true;
1201 }
1202
Douglas Gregor033f56d2008-12-23 00:53:59 +00001203 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001204 // differences in the argument and result types are in Objective-C
1205 // pointer conversions. If so, we permit the conversion (but
1206 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001207 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001208 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001209 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001210 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001211 if (FromFunctionType && ToFunctionType) {
1212 // If the function types are exactly the same, this isn't an
1213 // Objective-C pointer conversion.
1214 if (Context.getCanonicalType(FromPointeeType)
1215 == Context.getCanonicalType(ToPointeeType))
1216 return false;
1217
1218 // Perform the quick checks that will tell us whether these
1219 // function types are obviously different.
1220 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1221 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1222 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1223 return false;
1224
1225 bool HasObjCConversion = false;
1226 if (Context.getCanonicalType(FromFunctionType->getResultType())
1227 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1228 // Okay, the types match exactly. Nothing to do.
1229 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1230 ToFunctionType->getResultType(),
1231 ConvertedType, IncompatibleObjC)) {
1232 // Okay, we have an Objective-C pointer conversion.
1233 HasObjCConversion = true;
1234 } else {
1235 // Function types are too different. Abort.
1236 return false;
1237 }
Mike Stump11289f42009-09-09 15:08:12 +00001238
Douglas Gregora119f102008-12-19 19:13:09 +00001239 // Check argument types.
1240 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1241 ArgIdx != NumArgs; ++ArgIdx) {
1242 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1243 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1244 if (Context.getCanonicalType(FromArgType)
1245 == Context.getCanonicalType(ToArgType)) {
1246 // Okay, the types match exactly. Nothing to do.
1247 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1248 ConvertedType, IncompatibleObjC)) {
1249 // Okay, we have an Objective-C pointer conversion.
1250 HasObjCConversion = true;
1251 } else {
1252 // Argument types are too different. Abort.
1253 return false;
1254 }
1255 }
1256
1257 if (HasObjCConversion) {
1258 // We had an Objective-C conversion. Allow this pointer
1259 // conversion, but complain about it.
1260 ConvertedType = ToType;
1261 IncompatibleObjC = true;
1262 return true;
1263 }
1264 }
1265
Sebastian Redl72b597d2009-01-25 19:43:20 +00001266 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001267}
1268
Douglas Gregor39c16d42008-10-24 04:54:22 +00001269/// CheckPointerConversion - Check the pointer conversion from the
1270/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001271/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001272/// conversions for which IsPointerConversion has already returned
1273/// true. It returns true and produces a diagnostic if there was an
1274/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001275bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001276 CastExpr::CastKind &Kind,
1277 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001278 QualType FromType = From->getType();
1279
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001280 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1281 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001282 QualType FromPointeeType = FromPtrType->getPointeeType(),
1283 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001284
Douglas Gregor39c16d42008-10-24 04:54:22 +00001285 if (FromPointeeType->isRecordType() &&
1286 ToPointeeType->isRecordType()) {
1287 // We must have a derived-to-base conversion. Check an
1288 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001289 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1290 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001291 From->getSourceRange(),
1292 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001293 return true;
1294
1295 // The conversion was successful.
1296 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001297 }
1298 }
Mike Stump11289f42009-09-09 15:08:12 +00001299 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001300 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001301 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001302 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001303 // Objective-C++ conversions are always okay.
1304 // FIXME: We should have a different class of conversions for the
1305 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001306 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001307 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001308
Steve Naroff7cae42b2009-07-10 23:34:53 +00001309 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001310 return false;
1311}
1312
Sebastian Redl72b597d2009-01-25 19:43:20 +00001313/// IsMemberPointerConversion - Determines whether the conversion of the
1314/// expression From, which has the (possibly adjusted) type FromType, can be
1315/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1316/// If so, returns true and places the converted type (that might differ from
1317/// ToType in its cv-qualifiers at some level) into ConvertedType.
1318bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001319 QualType ToType,
1320 bool InOverloadResolution,
1321 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001322 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001323 if (!ToTypePtr)
1324 return false;
1325
1326 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001327 if (From->isNullPointerConstant(Context,
1328 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1329 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001330 ConvertedType = ToType;
1331 return true;
1332 }
1333
1334 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001335 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001336 if (!FromTypePtr)
1337 return false;
1338
1339 // A pointer to member of B can be converted to a pointer to member of D,
1340 // where D is derived from B (C++ 4.11p2).
1341 QualType FromClass(FromTypePtr->getClass(), 0);
1342 QualType ToClass(ToTypePtr->getClass(), 0);
1343 // FIXME: What happens when these are dependent? Is this function even called?
1344
1345 if (IsDerivedFrom(ToClass, FromClass)) {
1346 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1347 ToClass.getTypePtr());
1348 return true;
1349 }
1350
1351 return false;
1352}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001353
Sebastian Redl72b597d2009-01-25 19:43:20 +00001354/// CheckMemberPointerConversion - Check the member pointer conversion from the
1355/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001356/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001357/// for which IsMemberPointerConversion has already returned true. It returns
1358/// true and produces a diagnostic if there was an error, or returns false
1359/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001360bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001361 CastExpr::CastKind &Kind,
1362 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001363 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001364 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001365 if (!FromPtrType) {
1366 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001367 assert(From->isNullPointerConstant(Context,
1368 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001369 "Expr must be null pointer constant!");
1370 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001371 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001372 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001373
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001374 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001375 assert(ToPtrType && "No member pointer cast has a target type "
1376 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001377
Sebastian Redled8f2002009-01-28 18:33:18 +00001378 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1379 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001380
Sebastian Redled8f2002009-01-28 18:33:18 +00001381 // FIXME: What about dependent types?
1382 assert(FromClass->isRecordType() && "Pointer into non-class.");
1383 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001384
John McCall5b0829a2010-02-10 09:31:12 +00001385 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001386 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001387 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1388 assert(DerivationOkay &&
1389 "Should not have been called if derivation isn't OK.");
1390 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001391
Sebastian Redled8f2002009-01-28 18:33:18 +00001392 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1393 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001394 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1395 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1396 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1397 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001398 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001399
Douglas Gregor89ee6822009-02-28 01:32:25 +00001400 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001401 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1402 << FromClass << ToClass << QualType(VBase, 0)
1403 << From->getSourceRange();
1404 return true;
1405 }
1406
John McCall5b0829a2010-02-10 09:31:12 +00001407 if (!IgnoreBaseAccess)
1408 CheckBaseClassAccess(From->getExprLoc(), /*BaseToDerived*/ true,
1409 FromClass, ToClass, Paths.front());
1410
Anders Carlssond7923c62009-08-22 23:33:40 +00001411 // Must be a base to derived member conversion.
1412 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001413 return false;
1414}
1415
Douglas Gregor9a657932008-10-21 23:43:52 +00001416/// IsQualificationConversion - Determines whether the conversion from
1417/// an rvalue of type FromType to ToType is a qualification conversion
1418/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001419bool
1420Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001421 FromType = Context.getCanonicalType(FromType);
1422 ToType = Context.getCanonicalType(ToType);
1423
1424 // If FromType and ToType are the same type, this is not a
1425 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001426 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001427 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001428
Douglas Gregor9a657932008-10-21 23:43:52 +00001429 // (C++ 4.4p4):
1430 // A conversion can add cv-qualifiers at levels other than the first
1431 // in multi-level pointers, subject to the following rules: [...]
1432 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001433 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001434 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001435 // Within each iteration of the loop, we check the qualifiers to
1436 // determine if this still looks like a qualification
1437 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001438 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001439 // until there are no more pointers or pointers-to-members left to
1440 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001441 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001442
1443 // -- for every j > 0, if const is in cv 1,j then const is in cv
1444 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001445 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001446 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001447
Douglas Gregor9a657932008-10-21 23:43:52 +00001448 // -- if the cv 1,j and cv 2,j are different, then const is in
1449 // every cv for 0 < k < j.
1450 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001451 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001452 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001453
Douglas Gregor9a657932008-10-21 23:43:52 +00001454 // Keep track of whether all prior cv-qualifiers in the "to" type
1455 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001456 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001457 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001458 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001459
1460 // We are left with FromType and ToType being the pointee types
1461 // after unwrapping the original FromType and ToType the same number
1462 // of types. If we unwrapped any pointers, and if FromType and
1463 // ToType have the same unqualified type (since we checked
1464 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001465 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001466}
1467
Douglas Gregor576e98c2009-01-30 23:27:23 +00001468/// Determines whether there is a user-defined conversion sequence
1469/// (C++ [over.ics.user]) that converts expression From to the type
1470/// ToType. If such a conversion exists, User will contain the
1471/// user-defined conversion sequence that performs such a conversion
1472/// and this routine will return true. Otherwise, this routine returns
1473/// false and User is unspecified.
1474///
1475/// \param AllowConversionFunctions true if the conversion should
1476/// consider conversion functions at all. If false, only constructors
1477/// will be considered.
1478///
1479/// \param AllowExplicit true if the conversion should consider C++0x
1480/// "explicit" conversion functions as well as non-explicit conversion
1481/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001482///
1483/// \param ForceRValue true if the expression should be treated as an rvalue
1484/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001485/// \param UserCast true if looking for user defined conversion for a static
1486/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001487OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1488 UserDefinedConversionSequence& User,
1489 OverloadCandidateSet& CandidateSet,
1490 bool AllowConversionFunctions,
1491 bool AllowExplicit,
1492 bool ForceRValue,
1493 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001494 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001495 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1496 // We're not going to find any constructors.
1497 } else if (CXXRecordDecl *ToRecordDecl
1498 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001499 // C++ [over.match.ctor]p1:
1500 // When objects of class type are direct-initialized (8.5), or
1501 // copy-initialized from an expression of the same or a
1502 // derived class type (8.5), overload resolution selects the
1503 // constructor. [...] For copy-initialization, the candidate
1504 // functions are all the converting constructors (12.3.1) of
1505 // that class. The argument list is the expression-list within
1506 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001507 bool SuppressUserConversions = !UserCast;
1508 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1509 IsDerivedFrom(From->getType(), ToType)) {
1510 SuppressUserConversions = false;
1511 AllowConversionFunctions = false;
1512 }
1513
Mike Stump11289f42009-09-09 15:08:12 +00001514 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001515 = Context.DeclarationNames.getCXXConstructorName(
1516 Context.getCanonicalType(ToType).getUnqualifiedType());
1517 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001518 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001519 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001520 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001521 // Find the constructor (which may be a template).
1522 CXXConstructorDecl *Constructor = 0;
1523 FunctionTemplateDecl *ConstructorTmpl
1524 = dyn_cast<FunctionTemplateDecl>(*Con);
1525 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001526 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001527 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1528 else
1529 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001530
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001531 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001532 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001533 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00001534 AddTemplateOverloadCandidate(ConstructorTmpl,
1535 ConstructorTmpl->getAccess(),
1536 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001537 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001538 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001539 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001540 // Allow one user-defined conversion when user specifies a
1541 // From->ToType conversion via an static cast (c-style, etc).
John McCallb89836b2010-01-26 01:37:31 +00001542 AddOverloadCandidate(Constructor, Constructor->getAccess(),
1543 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001544 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001545 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001546 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001547 }
1548 }
1549
Douglas Gregor576e98c2009-01-30 23:27:23 +00001550 if (!AllowConversionFunctions) {
1551 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001552 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1553 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001554 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001555 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001556 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001557 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001558 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001559 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1560 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001561 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001562 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001563 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001564 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001565 NamedDecl *D = *I;
1566 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1567 if (isa<UsingShadowDecl>(D))
1568 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1569
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001570 CXXConversionDecl *Conv;
1571 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001572 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001573 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1574 else
John McCalld14a8642009-11-21 08:51:07 +00001575 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001576
1577 if (AllowExplicit || !Conv->isExplicit()) {
1578 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00001579 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
1580 ActingContext, From, ToType,
1581 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001582 else
John McCallb89836b2010-01-26 01:37:31 +00001583 AddConversionCandidate(Conv, I.getAccess(), ActingContext,
1584 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001585 }
1586 }
1587 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001588 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001589
1590 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001591 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001592 case OR_Success:
1593 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001594 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001595 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1596 // C++ [over.ics.user]p1:
1597 // If the user-defined conversion is specified by a
1598 // constructor (12.3.1), the initial standard conversion
1599 // sequence converts the source type to the type required by
1600 // the argument of the constructor.
1601 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001602 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001603 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001604 User.EllipsisConversion = true;
1605 else {
1606 User.Before = Best->Conversions[0].Standard;
1607 User.EllipsisConversion = false;
1608 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001609 User.ConversionFunction = Constructor;
1610 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001611 User.After.setFromType(
1612 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001613 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001614 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001615 } else if (CXXConversionDecl *Conversion
1616 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1617 // C++ [over.ics.user]p1:
1618 //
1619 // [...] If the user-defined conversion is specified by a
1620 // conversion function (12.3.2), the initial standard
1621 // conversion sequence converts the source type to the
1622 // implicit object parameter of the conversion function.
1623 User.Before = Best->Conversions[0].Standard;
1624 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001625 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001626
1627 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001628 // The second standard conversion sequence converts the
1629 // result of the user-defined conversion to the target type
1630 // for the sequence. Since an implicit conversion sequence
1631 // is an initialization, the special rules for
1632 // initialization by user-defined conversion apply when
1633 // selecting the best user-defined conversion for a
1634 // user-defined conversion sequence (see 13.3.3 and
1635 // 13.3.3.1).
1636 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001637 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001638 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001639 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001640 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001643 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001644 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001645 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001646 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001647 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001648
1649 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001650 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001651 }
1652
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001653 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001654}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001655
1656bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001657Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001658 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001659 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001660 OverloadingResult OvResult =
1661 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1662 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001663 if (OvResult == OR_Ambiguous)
1664 Diag(From->getSourceRange().getBegin(),
1665 diag::err_typecheck_ambiguous_condition)
1666 << From->getType() << ToType << From->getSourceRange();
1667 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1668 Diag(From->getSourceRange().getBegin(),
1669 diag::err_typecheck_nonviable_condition)
1670 << From->getType() << ToType << From->getSourceRange();
1671 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001672 return false;
John McCallad907772010-01-12 07:18:19 +00001673 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001674 return true;
1675}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001676
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001677/// CompareImplicitConversionSequences - Compare two implicit
1678/// conversion sequences to determine whether one is better than the
1679/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001680ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001681Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1682 const ImplicitConversionSequence& ICS2)
1683{
1684 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1685 // conversion sequences (as defined in 13.3.3.1)
1686 // -- a standard conversion sequence (13.3.3.1.1) is a better
1687 // conversion sequence than a user-defined conversion sequence or
1688 // an ellipsis conversion sequence, and
1689 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1690 // conversion sequence than an ellipsis conversion sequence
1691 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001692 //
John McCall0d1da222010-01-12 00:44:57 +00001693 // C++0x [over.best.ics]p10:
1694 // For the purpose of ranking implicit conversion sequences as
1695 // described in 13.3.3.2, the ambiguous conversion sequence is
1696 // treated as a user-defined sequence that is indistinguishable
1697 // from any other user-defined conversion sequence.
1698 if (ICS1.getKind() < ICS2.getKind()) {
1699 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1700 return ImplicitConversionSequence::Better;
1701 } else if (ICS2.getKind() < ICS1.getKind()) {
1702 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1703 return ImplicitConversionSequence::Worse;
1704 }
1705
1706 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1707 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708
1709 // Two implicit conversion sequences of the same form are
1710 // indistinguishable conversion sequences unless one of the
1711 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001712 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001714 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715 // User-defined conversion sequence U1 is a better conversion
1716 // sequence than another user-defined conversion sequence U2 if
1717 // they contain the same user-defined conversion function or
1718 // constructor and if the second standard conversion sequence of
1719 // U1 is better than the second standard conversion sequence of
1720 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001721 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001722 ICS2.UserDefined.ConversionFunction)
1723 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1724 ICS2.UserDefined.After);
1725 }
1726
1727 return ImplicitConversionSequence::Indistinguishable;
1728}
1729
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001730// Per 13.3.3.2p3, compare the given standard conversion sequences to
1731// determine if one is a proper subset of the other.
1732static ImplicitConversionSequence::CompareKind
1733compareStandardConversionSubsets(ASTContext &Context,
1734 const StandardConversionSequence& SCS1,
1735 const StandardConversionSequence& SCS2) {
1736 ImplicitConversionSequence::CompareKind Result
1737 = ImplicitConversionSequence::Indistinguishable;
1738
1739 if (SCS1.Second != SCS2.Second) {
1740 if (SCS1.Second == ICK_Identity)
1741 Result = ImplicitConversionSequence::Better;
1742 else if (SCS2.Second == ICK_Identity)
1743 Result = ImplicitConversionSequence::Worse;
1744 else
1745 return ImplicitConversionSequence::Indistinguishable;
1746 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1747 return ImplicitConversionSequence::Indistinguishable;
1748
1749 if (SCS1.Third == SCS2.Third) {
1750 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1751 : ImplicitConversionSequence::Indistinguishable;
1752 }
1753
1754 if (SCS1.Third == ICK_Identity)
1755 return Result == ImplicitConversionSequence::Worse
1756 ? ImplicitConversionSequence::Indistinguishable
1757 : ImplicitConversionSequence::Better;
1758
1759 if (SCS2.Third == ICK_Identity)
1760 return Result == ImplicitConversionSequence::Better
1761 ? ImplicitConversionSequence::Indistinguishable
1762 : ImplicitConversionSequence::Worse;
1763
1764 return ImplicitConversionSequence::Indistinguishable;
1765}
1766
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001767/// CompareStandardConversionSequences - Compare two standard
1768/// conversion sequences to determine whether one is better than the
1769/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001770ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001771Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1772 const StandardConversionSequence& SCS2)
1773{
1774 // Standard conversion sequence S1 is a better conversion sequence
1775 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1776
1777 // -- S1 is a proper subsequence of S2 (comparing the conversion
1778 // sequences in the canonical form defined by 13.3.3.1.1,
1779 // excluding any Lvalue Transformation; the identity conversion
1780 // sequence is considered to be a subsequence of any
1781 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001782 if (ImplicitConversionSequence::CompareKind CK
1783 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1784 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001785
1786 // -- the rank of S1 is better than the rank of S2 (by the rules
1787 // defined below), or, if not that,
1788 ImplicitConversionRank Rank1 = SCS1.getRank();
1789 ImplicitConversionRank Rank2 = SCS2.getRank();
1790 if (Rank1 < Rank2)
1791 return ImplicitConversionSequence::Better;
1792 else if (Rank2 < Rank1)
1793 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001794
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001795 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1796 // are indistinguishable unless one of the following rules
1797 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001798
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001799 // A conversion that is not a conversion of a pointer, or
1800 // pointer to member, to bool is better than another conversion
1801 // that is such a conversion.
1802 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1803 return SCS2.isPointerConversionToBool()
1804 ? ImplicitConversionSequence::Better
1805 : ImplicitConversionSequence::Worse;
1806
Douglas Gregor5c407d92008-10-23 00:40:37 +00001807 // C++ [over.ics.rank]p4b2:
1808 //
1809 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001810 // conversion of B* to A* is better than conversion of B* to
1811 // void*, and conversion of A* to void* is better than conversion
1812 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001813 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001814 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001815 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001816 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001817 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1818 // Exactly one of the conversion sequences is a conversion to
1819 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001820 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1821 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001822 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1823 // Neither conversion sequence converts to a void pointer; compare
1824 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001825 if (ImplicitConversionSequence::CompareKind DerivedCK
1826 = CompareDerivedToBaseConversions(SCS1, SCS2))
1827 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001828 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1829 // Both conversion sequences are conversions to void
1830 // pointers. Compare the source types to determine if there's an
1831 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001832 QualType FromType1 = SCS1.getFromType();
1833 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001834
1835 // Adjust the types we're converting from via the array-to-pointer
1836 // conversion, if we need to.
1837 if (SCS1.First == ICK_Array_To_Pointer)
1838 FromType1 = Context.getArrayDecayedType(FromType1);
1839 if (SCS2.First == ICK_Array_To_Pointer)
1840 FromType2 = Context.getArrayDecayedType(FromType2);
1841
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001842 QualType FromPointee1
1843 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1844 QualType FromPointee2
1845 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001846
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001847 if (IsDerivedFrom(FromPointee2, FromPointee1))
1848 return ImplicitConversionSequence::Better;
1849 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1850 return ImplicitConversionSequence::Worse;
1851
1852 // Objective-C++: If one interface is more specific than the
1853 // other, it is the better one.
1854 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1855 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1856 if (FromIface1 && FromIface1) {
1857 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1858 return ImplicitConversionSequence::Better;
1859 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1860 return ImplicitConversionSequence::Worse;
1861 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001862 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001863
1864 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1865 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001866 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001867 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001868 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001869
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001870 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001871 // C++0x [over.ics.rank]p3b4:
1872 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1873 // implicit object parameter of a non-static member function declared
1874 // without a ref-qualifier, and S1 binds an rvalue reference to an
1875 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001876 // FIXME: We don't know if we're dealing with the implicit object parameter,
1877 // or if the member function in this case has a ref qualifier.
1878 // (Of course, we don't have ref qualifiers yet.)
1879 if (SCS1.RRefBinding != SCS2.RRefBinding)
1880 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1881 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001882
1883 // C++ [over.ics.rank]p3b4:
1884 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1885 // which the references refer are the same type except for
1886 // top-level cv-qualifiers, and the type to which the reference
1887 // initialized by S2 refers is more cv-qualified than the type
1888 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001889 QualType T1 = SCS1.getToType(2);
1890 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001891 T1 = Context.getCanonicalType(T1);
1892 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001893 Qualifiers T1Quals, T2Quals;
1894 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1895 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1896 if (UnqualT1 == UnqualT2) {
1897 // If the type is an array type, promote the element qualifiers to the type
1898 // for comparison.
1899 if (isa<ArrayType>(T1) && T1Quals)
1900 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1901 if (isa<ArrayType>(T2) && T2Quals)
1902 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001903 if (T2.isMoreQualifiedThan(T1))
1904 return ImplicitConversionSequence::Better;
1905 else if (T1.isMoreQualifiedThan(T2))
1906 return ImplicitConversionSequence::Worse;
1907 }
1908 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001909
1910 return ImplicitConversionSequence::Indistinguishable;
1911}
1912
1913/// CompareQualificationConversions - Compares two standard conversion
1914/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001915/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1916ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001917Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001918 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001919 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001920 // -- S1 and S2 differ only in their qualification conversion and
1921 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1922 // cv-qualification signature of type T1 is a proper subset of
1923 // the cv-qualification signature of type T2, and S1 is not the
1924 // deprecated string literal array-to-pointer conversion (4.2).
1925 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1926 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1927 return ImplicitConversionSequence::Indistinguishable;
1928
1929 // FIXME: the example in the standard doesn't use a qualification
1930 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001931 QualType T1 = SCS1.getToType(2);
1932 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001933 T1 = Context.getCanonicalType(T1);
1934 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001935 Qualifiers T1Quals, T2Quals;
1936 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1937 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001938
1939 // If the types are the same, we won't learn anything by unwrapped
1940 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001941 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001942 return ImplicitConversionSequence::Indistinguishable;
1943
Chandler Carruth607f38e2009-12-29 07:16:59 +00001944 // If the type is an array type, promote the element qualifiers to the type
1945 // for comparison.
1946 if (isa<ArrayType>(T1) && T1Quals)
1947 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1948 if (isa<ArrayType>(T2) && T2Quals)
1949 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1950
Mike Stump11289f42009-09-09 15:08:12 +00001951 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001952 = ImplicitConversionSequence::Indistinguishable;
1953 while (UnwrapSimilarPointerTypes(T1, T2)) {
1954 // Within each iteration of the loop, we check the qualifiers to
1955 // determine if this still looks like a qualification
1956 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001957 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001958 // until there are no more pointers or pointers-to-members left
1959 // to unwrap. This essentially mimics what
1960 // IsQualificationConversion does, but here we're checking for a
1961 // strict subset of qualifiers.
1962 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1963 // The qualifiers are the same, so this doesn't tell us anything
1964 // about how the sequences rank.
1965 ;
1966 else if (T2.isMoreQualifiedThan(T1)) {
1967 // T1 has fewer qualifiers, so it could be the better sequence.
1968 if (Result == ImplicitConversionSequence::Worse)
1969 // Neither has qualifiers that are a subset of the other's
1970 // qualifiers.
1971 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001972
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001973 Result = ImplicitConversionSequence::Better;
1974 } else if (T1.isMoreQualifiedThan(T2)) {
1975 // T2 has fewer qualifiers, so it could be the better sequence.
1976 if (Result == ImplicitConversionSequence::Better)
1977 // Neither has qualifiers that are a subset of the other's
1978 // qualifiers.
1979 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001980
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001981 Result = ImplicitConversionSequence::Worse;
1982 } else {
1983 // Qualifiers are disjoint.
1984 return ImplicitConversionSequence::Indistinguishable;
1985 }
1986
1987 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001988 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001989 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001990 }
1991
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001992 // Check that the winning standard conversion sequence isn't using
1993 // the deprecated string literal array to pointer conversion.
1994 switch (Result) {
1995 case ImplicitConversionSequence::Better:
1996 if (SCS1.Deprecated)
1997 Result = ImplicitConversionSequence::Indistinguishable;
1998 break;
1999
2000 case ImplicitConversionSequence::Indistinguishable:
2001 break;
2002
2003 case ImplicitConversionSequence::Worse:
2004 if (SCS2.Deprecated)
2005 Result = ImplicitConversionSequence::Indistinguishable;
2006 break;
2007 }
2008
2009 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002010}
2011
Douglas Gregor5c407d92008-10-23 00:40:37 +00002012/// CompareDerivedToBaseConversions - Compares two standard conversion
2013/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002014/// various kinds of derived-to-base conversions (C++
2015/// [over.ics.rank]p4b3). As part of these checks, we also look at
2016/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002017ImplicitConversionSequence::CompareKind
2018Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2019 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002020 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002021 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002022 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002023 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002024
2025 // Adjust the types we're converting from via the array-to-pointer
2026 // conversion, if we need to.
2027 if (SCS1.First == ICK_Array_To_Pointer)
2028 FromType1 = Context.getArrayDecayedType(FromType1);
2029 if (SCS2.First == ICK_Array_To_Pointer)
2030 FromType2 = Context.getArrayDecayedType(FromType2);
2031
2032 // Canonicalize all of the types.
2033 FromType1 = Context.getCanonicalType(FromType1);
2034 ToType1 = Context.getCanonicalType(ToType1);
2035 FromType2 = Context.getCanonicalType(FromType2);
2036 ToType2 = Context.getCanonicalType(ToType2);
2037
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002038 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002039 //
2040 // If class B is derived directly or indirectly from class A and
2041 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002042 //
2043 // For Objective-C, we let A, B, and C also be Objective-C
2044 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002045
2046 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002047 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002048 SCS2.Second == ICK_Pointer_Conversion &&
2049 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2050 FromType1->isPointerType() && FromType2->isPointerType() &&
2051 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002052 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002053 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002054 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002055 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002056 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002057 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002058 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002059 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002060
John McCall9dd450b2009-09-21 23:43:11 +00002061 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2062 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2063 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2064 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002065
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002066 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002067 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2068 if (IsDerivedFrom(ToPointee1, ToPointee2))
2069 return ImplicitConversionSequence::Better;
2070 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2071 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002072
2073 if (ToIface1 && ToIface2) {
2074 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2075 return ImplicitConversionSequence::Better;
2076 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2077 return ImplicitConversionSequence::Worse;
2078 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002079 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002080
2081 // -- conversion of B* to A* is better than conversion of C* to A*,
2082 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2083 if (IsDerivedFrom(FromPointee2, FromPointee1))
2084 return ImplicitConversionSequence::Better;
2085 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2086 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002087
Douglas Gregor237f96c2008-11-26 23:31:11 +00002088 if (FromIface1 && FromIface2) {
2089 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2090 return ImplicitConversionSequence::Better;
2091 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2092 return ImplicitConversionSequence::Worse;
2093 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002094 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002095 }
2096
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002097 // Compare based on reference bindings.
2098 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2099 SCS1.Second == ICK_Derived_To_Base) {
2100 // -- binding of an expression of type C to a reference of type
2101 // B& is better than binding an expression of type C to a
2102 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002103 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2104 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002105 if (IsDerivedFrom(ToType1, ToType2))
2106 return ImplicitConversionSequence::Better;
2107 else if (IsDerivedFrom(ToType2, ToType1))
2108 return ImplicitConversionSequence::Worse;
2109 }
2110
Douglas Gregor2fe98832008-11-03 19:09:14 +00002111 // -- binding of an expression of type B to a reference of type
2112 // A& is better than binding an expression of type C to a
2113 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002114 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2115 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002116 if (IsDerivedFrom(FromType2, FromType1))
2117 return ImplicitConversionSequence::Better;
2118 else if (IsDerivedFrom(FromType1, FromType2))
2119 return ImplicitConversionSequence::Worse;
2120 }
2121 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002122
2123 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002124 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2125 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2126 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2127 const MemberPointerType * FromMemPointer1 =
2128 FromType1->getAs<MemberPointerType>();
2129 const MemberPointerType * ToMemPointer1 =
2130 ToType1->getAs<MemberPointerType>();
2131 const MemberPointerType * FromMemPointer2 =
2132 FromType2->getAs<MemberPointerType>();
2133 const MemberPointerType * ToMemPointer2 =
2134 ToType2->getAs<MemberPointerType>();
2135 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2136 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2137 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2138 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2139 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2140 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2141 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2142 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002143 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002144 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2145 if (IsDerivedFrom(ToPointee1, ToPointee2))
2146 return ImplicitConversionSequence::Worse;
2147 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2148 return ImplicitConversionSequence::Better;
2149 }
2150 // conversion of B::* to C::* is better than conversion of A::* to C::*
2151 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2152 if (IsDerivedFrom(FromPointee1, FromPointee2))
2153 return ImplicitConversionSequence::Better;
2154 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2155 return ImplicitConversionSequence::Worse;
2156 }
2157 }
2158
Douglas Gregor2fe98832008-11-03 19:09:14 +00002159 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2160 SCS1.Second == ICK_Derived_To_Base) {
2161 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002162 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2163 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002164 if (IsDerivedFrom(ToType1, ToType2))
2165 return ImplicitConversionSequence::Better;
2166 else if (IsDerivedFrom(ToType2, ToType1))
2167 return ImplicitConversionSequence::Worse;
2168 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002169
Douglas Gregor2fe98832008-11-03 19:09:14 +00002170 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002171 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2172 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002173 if (IsDerivedFrom(FromType2, FromType1))
2174 return ImplicitConversionSequence::Better;
2175 else if (IsDerivedFrom(FromType1, FromType2))
2176 return ImplicitConversionSequence::Worse;
2177 }
2178 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002179
Douglas Gregor5c407d92008-10-23 00:40:37 +00002180 return ImplicitConversionSequence::Indistinguishable;
2181}
2182
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002183/// TryCopyInitialization - Try to copy-initialize a value of type
2184/// ToType from the expression From. Return the implicit conversion
2185/// sequence required to pass this argument, which may be a bad
2186/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002187/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002188/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2189/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002190ImplicitConversionSequence
2191Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002192 bool SuppressUserConversions, bool ForceRValue,
2193 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002194 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002195 ImplicitConversionSequence ICS;
John McCall65eb8792010-02-25 01:37:24 +00002196 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002197 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002198 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002199 SuppressUserConversions,
2200 /*AllowExplicit=*/false,
2201 ForceRValue,
2202 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002203 return ICS;
2204 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002205 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002206 SuppressUserConversions,
2207 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002208 ForceRValue,
2209 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002210 }
2211}
2212
Sebastian Redl42e92c42009-04-12 17:16:29 +00002213/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2214/// the expression @p From. Returns true (and emits a diagnostic) if there was
2215/// an error, returns false if the initialization succeeded. Elidable should
2216/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2217/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002218bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002219 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002220 if (!getLangOptions().CPlusPlus) {
2221 // In C, argument passing is the same as performing an assignment.
2222 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002223
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002224 AssignConvertType ConvTy =
2225 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002226 if (ConvTy != Compatible &&
2227 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2228 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002229
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002230 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002231 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002232 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002233
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002234 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002235 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002236 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002237 /*SuppressUserConversions=*/false,
2238 /*AllowExplicit=*/false,
2239 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002240
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002241 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002242 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002243 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002244 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002245 return Diag(From->getSourceRange().getBegin(),
2246 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002247 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002248 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002249}
2250
Douglas Gregor436424c2008-11-18 23:14:02 +00002251/// TryObjectArgumentInitialization - Try to initialize the object
2252/// parameter of the given member function (@c Method) from the
2253/// expression @p From.
2254ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002255Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002256 CXXMethodDecl *Method,
2257 CXXRecordDecl *ActingContext) {
2258 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002259 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2260 // const volatile object.
2261 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2262 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2263 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002264
2265 // Set up the conversion sequence as a "bad" conversion, to allow us
2266 // to exit early.
2267 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002268
2269 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002270 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002271 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002272 FromType = PT->getPointeeType();
2273
2274 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002275
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002276 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002277 // where X is the class of which the function is a member
2278 // (C++ [over.match.funcs]p4). However, when finding an implicit
2279 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002280 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002281 // (C++ [over.match.funcs]p5). We perform a simplified version of
2282 // reference binding here, that allows class rvalues to bind to
2283 // non-constant references.
2284
2285 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2286 // with the implicit object parameter (C++ [over.match.funcs]p5).
2287 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002288 if (ImplicitParamType.getCVRQualifiers()
2289 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002290 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002291 ICS.setBad(BadConversionSequence::bad_qualifiers,
2292 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002293 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002294 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002295
2296 // Check that we have either the same type or a derived type. It
2297 // affects the conversion rank.
2298 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002299 ImplicitConversionKind SecondKind;
2300 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2301 SecondKind = ICK_Identity;
2302 } else if (IsDerivedFrom(FromType, ClassType))
2303 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002304 else {
John McCall65eb8792010-02-25 01:37:24 +00002305 ICS.setBad(BadConversionSequence::unrelated_class,
2306 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002307 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002308 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002309
2310 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002311 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002312 ICS.Standard.setAsIdentityConversion();
2313 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002314 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002315 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002316 ICS.Standard.ReferenceBinding = true;
2317 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002318 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002319 return ICS;
2320}
2321
2322/// PerformObjectArgumentInitialization - Perform initialization of
2323/// the implicit object parameter for the given Method with the given
2324/// expression.
2325bool
2326Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002327 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002328 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002329 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002330
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002331 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002332 FromRecordType = PT->getPointeeType();
2333 DestType = Method->getThisType(Context);
2334 } else {
2335 FromRecordType = From->getType();
2336 DestType = ImplicitParamRecordType;
2337 }
2338
John McCall6e9f8f62009-12-03 04:06:58 +00002339 // Note that we always use the true parent context when performing
2340 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002341 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002342 = TryObjectArgumentInitialization(From->getType(), Method,
2343 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002344 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002345 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002346 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002347 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002348
Douglas Gregor436424c2008-11-18 23:14:02 +00002349 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002350 CheckDerivedToBaseConversion(FromRecordType,
2351 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002352 From->getSourceRange().getBegin(),
2353 From->getSourceRange()))
2354 return true;
2355
Mike Stump11289f42009-09-09 15:08:12 +00002356 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002357 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002358 return false;
2359}
2360
Douglas Gregor5fb53972009-01-14 15:45:31 +00002361/// TryContextuallyConvertToBool - Attempt to contextually convert the
2362/// expression From to bool (C++0x [conv]p3).
2363ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002364 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002365 // FIXME: Are these flags correct?
2366 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002367 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002368 /*ForceRValue=*/false,
2369 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002370}
2371
2372/// PerformContextuallyConvertToBool - Perform a contextual conversion
2373/// of the expression From to bool (C++0x [conv]p3).
2374bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2375 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002376 if (!ICS.isBad())
2377 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002378
Fariborz Jahanian76197412009-11-18 18:26:29 +00002379 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002380 return Diag(From->getSourceRange().getBegin(),
2381 diag::err_typecheck_bool_condition)
2382 << From->getType() << From->getSourceRange();
2383 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002384}
2385
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002386/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002387/// candidate functions, using the given function call arguments. If
2388/// @p SuppressUserConversions, then don't allow user-defined
2389/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002390/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2391/// hacky way to implement the overloading rules for elidable copy
2392/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002393///
2394/// \para PartialOverloading true if we are performing "partial" overloading
2395/// based on an incomplete set of function arguments. This feature is used by
2396/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002397void
2398Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCallb89836b2010-01-26 01:37:31 +00002399 AccessSpecifier Access,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002400 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002401 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002402 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002403 bool ForceRValue,
2404 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002405 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002406 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002407 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002408 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002409 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002410
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002411 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002412 if (!isa<CXXConstructorDecl>(Method)) {
2413 // If we get here, it's because we're calling a member function
2414 // that is named without a member access expression (e.g.,
2415 // "this->f") that was either written explicitly or created
2416 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002417 // function, e.g., X::f(). We use an empty type for the implied
2418 // object argument (C++ [over.call.func]p3), and the acting context
2419 // is irrelevant.
John McCallb89836b2010-01-26 01:37:31 +00002420 AddMethodCandidate(Method, Access, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002421 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002422 SuppressUserConversions, ForceRValue);
2423 return;
2424 }
2425 // We treat a constructor like a non-member function, since its object
2426 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002427 }
2428
Douglas Gregorff7028a2009-11-13 23:59:09 +00002429 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002430 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002431
Douglas Gregor27381f32009-11-23 12:27:39 +00002432 // Overload resolution is always an unevaluated context.
2433 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2434
Douglas Gregorffe14e32009-11-14 01:20:54 +00002435 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2436 // C++ [class.copy]p3:
2437 // A member function template is never instantiated to perform the copy
2438 // of a class object to an object of its class type.
2439 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2440 if (NumArgs == 1 &&
2441 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002442 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2443 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002444 return;
2445 }
2446
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002447 // Add this candidate
2448 CandidateSet.push_back(OverloadCandidate());
2449 OverloadCandidate& Candidate = CandidateSet.back();
2450 Candidate.Function = Function;
John McCallb89836b2010-01-26 01:37:31 +00002451 Candidate.Access = Access;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002452 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002453 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002454 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002455
2456 unsigned NumArgsInProto = Proto->getNumArgs();
2457
2458 // (C++ 13.3.2p2): A candidate function having fewer than m
2459 // parameters is viable only if it has an ellipsis in its parameter
2460 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002461 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2462 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002463 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002464 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002465 return;
2466 }
2467
2468 // (C++ 13.3.2p2): A candidate function having more than m parameters
2469 // is viable only if the (m+1)st parameter has a default argument
2470 // (8.3.6). For the purposes of overload resolution, the
2471 // parameter list is truncated on the right, so that there are
2472 // exactly m parameters.
2473 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002474 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002475 // Not enough arguments.
2476 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002477 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002478 return;
2479 }
2480
2481 // Determine the implicit conversion sequences for each of the
2482 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002483 Candidate.Conversions.resize(NumArgs);
2484 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2485 if (ArgIdx < NumArgsInProto) {
2486 // (C++ 13.3.2p3): for F to be a viable function, there shall
2487 // exist for each argument an implicit conversion sequence
2488 // (13.3.3.1) that converts that argument to the corresponding
2489 // parameter of F.
2490 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002491 Candidate.Conversions[ArgIdx]
2492 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002493 SuppressUserConversions, ForceRValue,
2494 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002495 if (Candidate.Conversions[ArgIdx].isBad()) {
2496 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002497 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002498 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002499 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002500 } else {
2501 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2502 // argument for which there is no corresponding parameter is
2503 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002504 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002505 }
2506 }
2507}
2508
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002509/// \brief Add all of the function declarations in the given function set to
2510/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002511void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002512 Expr **Args, unsigned NumArgs,
2513 OverloadCandidateSet& CandidateSet,
2514 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002515 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002516 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002517 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2518 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002519 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002520 cast<CXXMethodDecl>(FD)->getParent(),
2521 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002522 CandidateSet, SuppressUserConversions);
2523 else
John McCallb89836b2010-01-26 01:37:31 +00002524 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002525 SuppressUserConversions);
2526 } else {
2527 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2528 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2529 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002530 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002531 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002532 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002533 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002534 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002535 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002536 else
John McCallb89836b2010-01-26 01:37:31 +00002537 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCall6b51f282009-11-23 01:53:49 +00002538 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002539 Args, NumArgs, CandidateSet,
2540 SuppressUserConversions);
2541 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002542 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002543}
2544
John McCallf0f1cf02009-11-17 07:50:12 +00002545/// AddMethodCandidate - Adds a named decl (which is some kind of
2546/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002547void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCallb89836b2010-01-26 01:37:31 +00002548 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002549 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002550 Expr **Args, unsigned NumArgs,
2551 OverloadCandidateSet& CandidateSet,
2552 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002553 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002554
2555 if (isa<UsingShadowDecl>(Decl))
2556 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2557
2558 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2559 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2560 "Expected a member function template");
John McCallb89836b2010-01-26 01:37:31 +00002561 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002562 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002563 CandidateSet,
2564 SuppressUserConversions,
2565 ForceRValue);
2566 } else {
John McCallb89836b2010-01-26 01:37:31 +00002567 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002568 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002569 CandidateSet, SuppressUserConversions, ForceRValue);
2570 }
2571}
2572
Douglas Gregor436424c2008-11-18 23:14:02 +00002573/// AddMethodCandidate - Adds the given C++ member function to the set
2574/// of candidate functions, using the given function call arguments
2575/// and the object argument (@c Object). For example, in a call
2576/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2577/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2578/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002579/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2580/// a slightly hacky way to implement the overloading rules for elidable copy
2581/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002582void
John McCallb89836b2010-01-26 01:37:31 +00002583Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2584 CXXRecordDecl *ActingContext, QualType ObjectType,
2585 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002586 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002587 bool SuppressUserConversions, bool ForceRValue) {
2588 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002589 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002590 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002591 assert(!isa<CXXConstructorDecl>(Method) &&
2592 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002593
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002594 if (!CandidateSet.isNewCandidate(Method))
2595 return;
2596
Douglas Gregor27381f32009-11-23 12:27:39 +00002597 // Overload resolution is always an unevaluated context.
2598 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2599
Douglas Gregor436424c2008-11-18 23:14:02 +00002600 // Add this candidate
2601 CandidateSet.push_back(OverloadCandidate());
2602 OverloadCandidate& Candidate = CandidateSet.back();
2603 Candidate.Function = Method;
John McCallb89836b2010-01-26 01:37:31 +00002604 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002605 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002606 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002607
2608 unsigned NumArgsInProto = Proto->getNumArgs();
2609
2610 // (C++ 13.3.2p2): A candidate function having fewer than m
2611 // parameters is viable only if it has an ellipsis in its parameter
2612 // list (8.3.5).
2613 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2614 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002615 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002616 return;
2617 }
2618
2619 // (C++ 13.3.2p2): A candidate function having more than m parameters
2620 // is viable only if the (m+1)st parameter has a default argument
2621 // (8.3.6). For the purposes of overload resolution, the
2622 // parameter list is truncated on the right, so that there are
2623 // exactly m parameters.
2624 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2625 if (NumArgs < MinRequiredArgs) {
2626 // Not enough arguments.
2627 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002628 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002629 return;
2630 }
2631
2632 Candidate.Viable = true;
2633 Candidate.Conversions.resize(NumArgs + 1);
2634
John McCall6e9f8f62009-12-03 04:06:58 +00002635 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002636 // The implicit object argument is ignored.
2637 Candidate.IgnoreObjectArgument = true;
2638 else {
2639 // Determine the implicit conversion sequence for the object
2640 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002641 Candidate.Conversions[0]
2642 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002643 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002644 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002645 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002646 return;
2647 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002648 }
2649
2650 // Determine the implicit conversion sequences for each of the
2651 // arguments.
2652 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2653 if (ArgIdx < NumArgsInProto) {
2654 // (C++ 13.3.2p3): for F to be a viable function, there shall
2655 // exist for each argument an implicit conversion sequence
2656 // (13.3.3.1) that converts that argument to the corresponding
2657 // parameter of F.
2658 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002659 Candidate.Conversions[ArgIdx + 1]
2660 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002661 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002662 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002663 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002664 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002665 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002666 break;
2667 }
2668 } else {
2669 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2670 // argument for which there is no corresponding parameter is
2671 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002672 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002673 }
2674 }
2675}
2676
Douglas Gregor97628d62009-08-21 00:16:32 +00002677/// \brief Add a C++ member function template as a candidate to the candidate
2678/// set, using template argument deduction to produce an appropriate member
2679/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002680void
Douglas Gregor97628d62009-08-21 00:16:32 +00002681Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCallb89836b2010-01-26 01:37:31 +00002682 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002683 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002684 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002685 QualType ObjectType,
2686 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002687 OverloadCandidateSet& CandidateSet,
2688 bool SuppressUserConversions,
2689 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002690 if (!CandidateSet.isNewCandidate(MethodTmpl))
2691 return;
2692
Douglas Gregor97628d62009-08-21 00:16:32 +00002693 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002694 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002695 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002696 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002697 // candidate functions in the usual way.113) A given name can refer to one
2698 // or more function templates and also to a set of overloaded non-template
2699 // functions. In such a case, the candidate functions generated from each
2700 // function template are combined with the set of non-template candidate
2701 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002702 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00002703 FunctionDecl *Specialization = 0;
2704 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002705 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002706 Args, NumArgs, Specialization, Info)) {
2707 // FIXME: Record what happened with template argument deduction, so
2708 // that we can give the user a beautiful diagnostic.
2709 (void)Result;
2710 return;
2711 }
Mike Stump11289f42009-09-09 15:08:12 +00002712
Douglas Gregor97628d62009-08-21 00:16:32 +00002713 // Add the function template specialization produced by template argument
2714 // deduction as a candidate.
2715 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002716 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002717 "Specialization is not a member function?");
John McCallb89836b2010-01-26 01:37:31 +00002718 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2719 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002720 CandidateSet, SuppressUserConversions, ForceRValue);
2721}
2722
Douglas Gregor05155d82009-08-21 23:19:43 +00002723/// \brief Add a C++ function template specialization as a candidate
2724/// in the candidate set, using template argument deduction to produce
2725/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002726void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002727Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002728 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00002729 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002730 Expr **Args, unsigned NumArgs,
2731 OverloadCandidateSet& CandidateSet,
2732 bool SuppressUserConversions,
2733 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002734 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2735 return;
2736
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002737 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002738 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002739 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002740 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002741 // candidate functions in the usual way.113) A given name can refer to one
2742 // or more function templates and also to a set of overloaded non-template
2743 // functions. In such a case, the candidate functions generated from each
2744 // function template are combined with the set of non-template candidate
2745 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002746 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002747 FunctionDecl *Specialization = 0;
2748 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002749 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002750 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00002751 CandidateSet.push_back(OverloadCandidate());
2752 OverloadCandidate &Candidate = CandidateSet.back();
2753 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCallb89836b2010-01-26 01:37:31 +00002754 Candidate.Access = Access;
John McCalld681c392009-12-16 08:11:27 +00002755 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002756 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002757 Candidate.IsSurrogate = false;
2758 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00002759
2760 // TODO: record more information about failed template arguments
2761 Candidate.DeductionFailure.Result = Result;
2762 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002763 return;
2764 }
Mike Stump11289f42009-09-09 15:08:12 +00002765
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002766 // Add the function template specialization produced by template argument
2767 // deduction as a candidate.
2768 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002769 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002770 SuppressUserConversions, ForceRValue);
2771}
Mike Stump11289f42009-09-09 15:08:12 +00002772
Douglas Gregora1f013e2008-11-07 22:36:19 +00002773/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002774/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002775/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002776/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002777/// (which may or may not be the same type as the type that the
2778/// conversion function produces).
2779void
2780Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002781 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002782 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002783 Expr *From, QualType ToType,
2784 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002785 assert(!Conversion->getDescribedFunctionTemplate() &&
2786 "Conversion function templates use AddTemplateConversionCandidate");
2787
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002788 if (!CandidateSet.isNewCandidate(Conversion))
2789 return;
2790
Douglas Gregor27381f32009-11-23 12:27:39 +00002791 // Overload resolution is always an unevaluated context.
2792 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2793
Douglas Gregora1f013e2008-11-07 22:36:19 +00002794 // Add this candidate
2795 CandidateSet.push_back(OverloadCandidate());
2796 OverloadCandidate& Candidate = CandidateSet.back();
2797 Candidate.Function = Conversion;
John McCallb89836b2010-01-26 01:37:31 +00002798 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002799 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002800 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002801 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002802 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002803 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002804
Douglas Gregor436424c2008-11-18 23:14:02 +00002805 // Determine the implicit conversion sequence for the implicit
2806 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002807 Candidate.Viable = true;
2808 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002809 Candidate.Conversions[0]
2810 = TryObjectArgumentInitialization(From->getType(), Conversion,
2811 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002812 // Conversion functions to a different type in the base class is visible in
2813 // the derived class. So, a derived to base conversion should not participate
2814 // in overload resolution.
2815 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2816 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002817 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002818 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002819 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002820 return;
2821 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002822
2823 // We won't go through a user-define type conversion function to convert a
2824 // derived to base as such conversions are given Conversion Rank. They only
2825 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2826 QualType FromCanon
2827 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2828 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2829 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2830 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002831 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002832 return;
2833 }
2834
Douglas Gregora1f013e2008-11-07 22:36:19 +00002835
2836 // To determine what the conversion from the result of calling the
2837 // conversion function to the type we're eventually trying to
2838 // convert to (ToType), we need to synthesize a call to the
2839 // conversion function and attempt copy initialization from it. This
2840 // makes sure that we get the right semantics with respect to
2841 // lvalues/rvalues and the type. Fortunately, we can allocate this
2842 // call on the stack and we don't need its arguments to be
2843 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002844 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002845 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002846 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002847 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002848 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002849
2850 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002851 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2852 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002853 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002854 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002855 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002856 ImplicitConversionSequence ICS =
2857 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002858 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002859 /*ForceRValue=*/false,
2860 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002861
John McCall0d1da222010-01-12 00:44:57 +00002862 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002863 case ImplicitConversionSequence::StandardConversion:
2864 Candidate.FinalConversion = ICS.Standard;
2865 break;
2866
2867 case ImplicitConversionSequence::BadConversion:
2868 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002869 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002870 break;
2871
2872 default:
Mike Stump11289f42009-09-09 15:08:12 +00002873 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002874 "Can only end up with a standard conversion sequence or failure");
2875 }
2876}
2877
Douglas Gregor05155d82009-08-21 23:19:43 +00002878/// \brief Adds a conversion function template specialization
2879/// candidate to the overload set, using template argument deduction
2880/// to deduce the template arguments of the conversion function
2881/// template from the type that we are converting to (C++
2882/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002883void
Douglas Gregor05155d82009-08-21 23:19:43 +00002884Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002885 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002886 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002887 Expr *From, QualType ToType,
2888 OverloadCandidateSet &CandidateSet) {
2889 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2890 "Only conversion function templates permitted here");
2891
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002892 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2893 return;
2894
John McCallbc077cf2010-02-08 23:07:23 +00002895 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00002896 CXXConversionDecl *Specialization = 0;
2897 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002898 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002899 Specialization, Info)) {
2900 // FIXME: Record what happened with template argument deduction, so
2901 // that we can give the user a beautiful diagnostic.
2902 (void)Result;
2903 return;
2904 }
Mike Stump11289f42009-09-09 15:08:12 +00002905
Douglas Gregor05155d82009-08-21 23:19:43 +00002906 // Add the conversion function template specialization produced by
2907 // template argument deduction as a candidate.
2908 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002909 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2910 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002911}
2912
Douglas Gregorab7897a2008-11-19 22:57:39 +00002913/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2914/// converts the given @c Object to a function pointer via the
2915/// conversion function @c Conversion, and then attempts to call it
2916/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2917/// the type of function that we'll eventually be calling.
2918void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002919 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002920 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002921 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002922 QualType ObjectType,
2923 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002924 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002925 if (!CandidateSet.isNewCandidate(Conversion))
2926 return;
2927
Douglas Gregor27381f32009-11-23 12:27:39 +00002928 // Overload resolution is always an unevaluated context.
2929 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2930
Douglas Gregorab7897a2008-11-19 22:57:39 +00002931 CandidateSet.push_back(OverloadCandidate());
2932 OverloadCandidate& Candidate = CandidateSet.back();
2933 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00002934 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002935 Candidate.Surrogate = Conversion;
2936 Candidate.Viable = true;
2937 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002938 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002939 Candidate.Conversions.resize(NumArgs + 1);
2940
2941 // Determine the implicit conversion sequence for the implicit
2942 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002943 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002944 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002945 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002946 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002947 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00002948 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002949 return;
2950 }
2951
2952 // The first conversion is actually a user-defined conversion whose
2953 // first conversion is ObjectInit's standard conversion (which is
2954 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002955 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002956 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002957 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002958 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002959 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002960 = Candidate.Conversions[0].UserDefined.Before;
2961 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2962
Mike Stump11289f42009-09-09 15:08:12 +00002963 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002964 unsigned NumArgsInProto = Proto->getNumArgs();
2965
2966 // (C++ 13.3.2p2): A candidate function having fewer than m
2967 // parameters is viable only if it has an ellipsis in its parameter
2968 // list (8.3.5).
2969 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2970 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002971 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002972 return;
2973 }
2974
2975 // Function types don't have any default arguments, so just check if
2976 // we have enough arguments.
2977 if (NumArgs < NumArgsInProto) {
2978 // Not enough arguments.
2979 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002980 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002981 return;
2982 }
2983
2984 // Determine the implicit conversion sequences for each of the
2985 // arguments.
2986 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2987 if (ArgIdx < NumArgsInProto) {
2988 // (C++ 13.3.2p3): for F to be a viable function, there shall
2989 // exist for each argument an implicit conversion sequence
2990 // (13.3.3.1) that converts that argument to the corresponding
2991 // parameter of F.
2992 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002993 Candidate.Conversions[ArgIdx + 1]
2994 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002995 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002996 /*ForceRValue=*/false,
2997 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002998 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002999 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003000 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003001 break;
3002 }
3003 } else {
3004 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3005 // argument for which there is no corresponding parameter is
3006 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003007 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003008 }
3009 }
3010}
3011
Mike Stump87c57ac2009-05-16 07:39:55 +00003012// FIXME: This will eventually be removed, once we've migrated all of the
3013// operator overloading logic over to the scheme used by binary operators, which
3014// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003015void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003016 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003017 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003018 OverloadCandidateSet& CandidateSet,
3019 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003020 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003021
3022 QualType T1 = Args[0]->getType();
3023 QualType T2;
3024 if (NumArgs > 1)
3025 T2 = Args[1]->getType();
3026
3027 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003028 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003029 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3030 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3031 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3032 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003033 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003034 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003035}
3036
3037/// \brief Add overload candidates for overloaded operators that are
3038/// member functions.
3039///
3040/// Add the overloaded operator candidates that are member functions
3041/// for the operator Op that was used in an operator expression such
3042/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3043/// CandidateSet will store the added overload candidates. (C++
3044/// [over.match.oper]).
3045void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3046 SourceLocation OpLoc,
3047 Expr **Args, unsigned NumArgs,
3048 OverloadCandidateSet& CandidateSet,
3049 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003050 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3051
3052 // C++ [over.match.oper]p3:
3053 // For a unary operator @ with an operand of a type whose
3054 // cv-unqualified version is T1, and for a binary operator @ with
3055 // a left operand of a type whose cv-unqualified version is T1 and
3056 // a right operand of a type whose cv-unqualified version is T2,
3057 // three sets of candidate functions, designated member
3058 // candidates, non-member candidates and built-in candidates, are
3059 // constructed as follows:
3060 QualType T1 = Args[0]->getType();
3061 QualType T2;
3062 if (NumArgs > 1)
3063 T2 = Args[1]->getType();
3064
3065 // -- If T1 is a class type, the set of member candidates is the
3066 // result of the qualified lookup of T1::operator@
3067 // (13.3.1.1.1); otherwise, the set of member candidates is
3068 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003069 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003070 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003071 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003072 return;
Mike Stump11289f42009-09-09 15:08:12 +00003073
John McCall27b18f82009-11-17 02:14:36 +00003074 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3075 LookupQualifiedName(Operators, T1Rec->getDecl());
3076 Operators.suppressDiagnostics();
3077
Mike Stump11289f42009-09-09 15:08:12 +00003078 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003079 OperEnd = Operators.end();
3080 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003081 ++Oper)
John McCallb89836b2010-01-26 01:37:31 +00003082 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003083 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003084 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003085 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003086}
3087
Douglas Gregora11693b2008-11-12 17:17:38 +00003088/// AddBuiltinCandidate - Add a candidate for a built-in
3089/// operator. ResultTy and ParamTys are the result and parameter types
3090/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003091/// arguments being passed to the candidate. IsAssignmentOperator
3092/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003093/// operator. NumContextualBoolArguments is the number of arguments
3094/// (at the beginning of the argument list) that will be contextually
3095/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003096void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003097 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003098 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003099 bool IsAssignmentOperator,
3100 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003101 // Overload resolution is always an unevaluated context.
3102 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3103
Douglas Gregora11693b2008-11-12 17:17:38 +00003104 // Add this candidate
3105 CandidateSet.push_back(OverloadCandidate());
3106 OverloadCandidate& Candidate = CandidateSet.back();
3107 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00003108 Candidate.Access = AS_none;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003109 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003110 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003111 Candidate.BuiltinTypes.ResultTy = ResultTy;
3112 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3113 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3114
3115 // Determine the implicit conversion sequences for each of the
3116 // arguments.
3117 Candidate.Viable = true;
3118 Candidate.Conversions.resize(NumArgs);
3119 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003120 // C++ [over.match.oper]p4:
3121 // For the built-in assignment operators, conversions of the
3122 // left operand are restricted as follows:
3123 // -- no temporaries are introduced to hold the left operand, and
3124 // -- no user-defined conversions are applied to the left
3125 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003126 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003127 //
3128 // We block these conversions by turning off user-defined
3129 // conversions, since that is the only way that initialization of
3130 // a reference to a non-class type can occur from something that
3131 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003132 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003133 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003134 "Contextual conversion to bool requires bool type");
3135 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3136 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003137 Candidate.Conversions[ArgIdx]
3138 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003139 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003140 /*ForceRValue=*/false,
3141 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003142 }
John McCall0d1da222010-01-12 00:44:57 +00003143 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003144 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003145 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003146 break;
3147 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003148 }
3149}
3150
3151/// BuiltinCandidateTypeSet - A set of types that will be used for the
3152/// candidate operator functions for built-in operators (C++
3153/// [over.built]). The types are separated into pointer types and
3154/// enumeration types.
3155class BuiltinCandidateTypeSet {
3156 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003157 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003158
3159 /// PointerTypes - The set of pointer types that will be used in the
3160 /// built-in candidates.
3161 TypeSet PointerTypes;
3162
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003163 /// MemberPointerTypes - The set of member pointer types that will be
3164 /// used in the built-in candidates.
3165 TypeSet MemberPointerTypes;
3166
Douglas Gregora11693b2008-11-12 17:17:38 +00003167 /// EnumerationTypes - The set of enumeration types that will be
3168 /// used in the built-in candidates.
3169 TypeSet EnumerationTypes;
3170
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003171 /// Sema - The semantic analysis instance where we are building the
3172 /// candidate type set.
3173 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003174
Douglas Gregora11693b2008-11-12 17:17:38 +00003175 /// Context - The AST context in which we will build the type sets.
3176 ASTContext &Context;
3177
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003178 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3179 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003180 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003181
3182public:
3183 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003184 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003185
Mike Stump11289f42009-09-09 15:08:12 +00003186 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003187 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003188
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003189 void AddTypesConvertedFrom(QualType Ty,
3190 SourceLocation Loc,
3191 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003192 bool AllowExplicitConversions,
3193 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003194
3195 /// pointer_begin - First pointer type found;
3196 iterator pointer_begin() { return PointerTypes.begin(); }
3197
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003198 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003199 iterator pointer_end() { return PointerTypes.end(); }
3200
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003201 /// member_pointer_begin - First member pointer type found;
3202 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3203
3204 /// member_pointer_end - Past the last member pointer type found;
3205 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3206
Douglas Gregora11693b2008-11-12 17:17:38 +00003207 /// enumeration_begin - First enumeration type found;
3208 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3209
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003210 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003211 iterator enumeration_end() { return EnumerationTypes.end(); }
3212};
3213
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003214/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003215/// the set of pointer types along with any more-qualified variants of
3216/// that type. For example, if @p Ty is "int const *", this routine
3217/// will add "int const *", "int const volatile *", "int const
3218/// restrict *", and "int const volatile restrict *" to the set of
3219/// pointer types. Returns true if the add of @p Ty itself succeeded,
3220/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003221///
3222/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003223bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003224BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3225 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003226
Douglas Gregora11693b2008-11-12 17:17:38 +00003227 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003228 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003229 return false;
3230
John McCall8ccfcb52009-09-24 19:53:00 +00003231 const PointerType *PointerTy = Ty->getAs<PointerType>();
3232 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003233
John McCall8ccfcb52009-09-24 19:53:00 +00003234 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003235 // Don't add qualified variants of arrays. For one, they're not allowed
3236 // (the qualifier would sink to the element type), and for another, the
3237 // only overload situation where it matters is subscript or pointer +- int,
3238 // and those shouldn't have qualifier variants anyway.
3239 if (PointeeTy->isArrayType())
3240 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003241 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003242 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003243 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003244 bool hasVolatile = VisibleQuals.hasVolatile();
3245 bool hasRestrict = VisibleQuals.hasRestrict();
3246
John McCall8ccfcb52009-09-24 19:53:00 +00003247 // Iterate through all strict supersets of BaseCVR.
3248 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3249 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003250 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3251 // in the types.
3252 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3253 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003254 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3255 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003256 }
3257
3258 return true;
3259}
3260
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003261/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3262/// to the set of pointer types along with any more-qualified variants of
3263/// that type. For example, if @p Ty is "int const *", this routine
3264/// will add "int const *", "int const volatile *", "int const
3265/// restrict *", and "int const volatile restrict *" to the set of
3266/// pointer types. Returns true if the add of @p Ty itself succeeded,
3267/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003268///
3269/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003270bool
3271BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3272 QualType Ty) {
3273 // Insert this type.
3274 if (!MemberPointerTypes.insert(Ty))
3275 return false;
3276
John McCall8ccfcb52009-09-24 19:53:00 +00003277 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3278 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003279
John McCall8ccfcb52009-09-24 19:53:00 +00003280 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003281 // Don't add qualified variants of arrays. For one, they're not allowed
3282 // (the qualifier would sink to the element type), and for another, the
3283 // only overload situation where it matters is subscript or pointer +- int,
3284 // and those shouldn't have qualifier variants anyway.
3285 if (PointeeTy->isArrayType())
3286 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003287 const Type *ClassTy = PointerTy->getClass();
3288
3289 // Iterate through all strict supersets of the pointee type's CVR
3290 // qualifiers.
3291 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3292 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3293 if ((CVR | BaseCVR) != CVR) continue;
3294
3295 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3296 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003297 }
3298
3299 return true;
3300}
3301
Douglas Gregora11693b2008-11-12 17:17:38 +00003302/// AddTypesConvertedFrom - Add each of the types to which the type @p
3303/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003304/// primarily interested in pointer types and enumeration types. We also
3305/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003306/// AllowUserConversions is true if we should look at the conversion
3307/// functions of a class type, and AllowExplicitConversions if we
3308/// should also include the explicit conversion functions of a class
3309/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003310void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003311BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003312 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003313 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003314 bool AllowExplicitConversions,
3315 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003316 // Only deal with canonical types.
3317 Ty = Context.getCanonicalType(Ty);
3318
3319 // Look through reference types; they aren't part of the type of an
3320 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003321 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003322 Ty = RefTy->getPointeeType();
3323
3324 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003325 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003326
Sebastian Redl65ae2002009-11-05 16:36:20 +00003327 // If we're dealing with an array type, decay to the pointer.
3328 if (Ty->isArrayType())
3329 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3330
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003331 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003332 QualType PointeeTy = PointerTy->getPointeeType();
3333
3334 // Insert our type, and its more-qualified variants, into the set
3335 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003336 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003337 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003338 } else if (Ty->isMemberPointerType()) {
3339 // Member pointers are far easier, since the pointee can't be converted.
3340 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3341 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003342 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003343 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003344 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003345 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003346 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003347 // No conversion functions in incomplete types.
3348 return;
3349 }
Mike Stump11289f42009-09-09 15:08:12 +00003350
Douglas Gregora11693b2008-11-12 17:17:38 +00003351 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003352 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003353 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003354 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003355 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003356
Mike Stump11289f42009-09-09 15:08:12 +00003357 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003358 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003359 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003360 continue;
3361
John McCalld14a8642009-11-21 08:51:07 +00003362 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003363 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003364 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003365 VisibleQuals);
3366 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003367 }
3368 }
3369 }
3370}
3371
Douglas Gregor84605ae2009-08-24 13:43:27 +00003372/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3373/// the volatile- and non-volatile-qualified assignment operators for the
3374/// given type to the candidate set.
3375static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3376 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003377 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003378 unsigned NumArgs,
3379 OverloadCandidateSet &CandidateSet) {
3380 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003381
Douglas Gregor84605ae2009-08-24 13:43:27 +00003382 // T& operator=(T&, T)
3383 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3384 ParamTypes[1] = T;
3385 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3386 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003387
Douglas Gregor84605ae2009-08-24 13:43:27 +00003388 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3389 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003390 ParamTypes[0]
3391 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003392 ParamTypes[1] = T;
3393 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003394 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003395 }
3396}
Mike Stump11289f42009-09-09 15:08:12 +00003397
Sebastian Redl1054fae2009-10-25 17:03:50 +00003398/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3399/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003400static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3401 Qualifiers VRQuals;
3402 const RecordType *TyRec;
3403 if (const MemberPointerType *RHSMPType =
3404 ArgExpr->getType()->getAs<MemberPointerType>())
3405 TyRec = cast<RecordType>(RHSMPType->getClass());
3406 else
3407 TyRec = ArgExpr->getType()->getAs<RecordType>();
3408 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003409 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003410 VRQuals.addVolatile();
3411 VRQuals.addRestrict();
3412 return VRQuals;
3413 }
3414
3415 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003416 if (!ClassDecl->hasDefinition())
3417 return VRQuals;
3418
John McCallad371252010-01-20 00:46:10 +00003419 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003420 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003421
John McCallad371252010-01-20 00:46:10 +00003422 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003423 E = Conversions->end(); I != E; ++I) {
3424 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003425 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3426 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3427 CanTy = ResTypeRef->getPointeeType();
3428 // Need to go down the pointer/mempointer chain and add qualifiers
3429 // as see them.
3430 bool done = false;
3431 while (!done) {
3432 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3433 CanTy = ResTypePtr->getPointeeType();
3434 else if (const MemberPointerType *ResTypeMPtr =
3435 CanTy->getAs<MemberPointerType>())
3436 CanTy = ResTypeMPtr->getPointeeType();
3437 else
3438 done = true;
3439 if (CanTy.isVolatileQualified())
3440 VRQuals.addVolatile();
3441 if (CanTy.isRestrictQualified())
3442 VRQuals.addRestrict();
3443 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3444 return VRQuals;
3445 }
3446 }
3447 }
3448 return VRQuals;
3449}
3450
Douglas Gregord08452f2008-11-19 15:42:04 +00003451/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3452/// operator overloads to the candidate set (C++ [over.built]), based
3453/// on the operator @p Op and the arguments given. For example, if the
3454/// operator is a binary '+', this routine might add "int
3455/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003456void
Mike Stump11289f42009-09-09 15:08:12 +00003457Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003458 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003459 Expr **Args, unsigned NumArgs,
3460 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003461 // The set of "promoted arithmetic types", which are the arithmetic
3462 // types are that preserved by promotion (C++ [over.built]p2). Note
3463 // that the first few of these types are the promoted integral
3464 // types; these types need to be first.
3465 // FIXME: What about complex?
3466 const unsigned FirstIntegralType = 0;
3467 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003468 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003469 LastPromotedIntegralType = 13;
3470 const unsigned FirstPromotedArithmeticType = 7,
3471 LastPromotedArithmeticType = 16;
3472 const unsigned NumArithmeticTypes = 16;
3473 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003474 Context.BoolTy, Context.CharTy, Context.WCharTy,
3475// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003476 Context.SignedCharTy, Context.ShortTy,
3477 Context.UnsignedCharTy, Context.UnsignedShortTy,
3478 Context.IntTy, Context.LongTy, Context.LongLongTy,
3479 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3480 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3481 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003482 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3483 "Invalid first promoted integral type");
3484 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3485 == Context.UnsignedLongLongTy &&
3486 "Invalid last promoted integral type");
3487 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3488 "Invalid first promoted arithmetic type");
3489 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3490 == Context.LongDoubleTy &&
3491 "Invalid last promoted arithmetic type");
3492
Douglas Gregora11693b2008-11-12 17:17:38 +00003493 // Find all of the types that the arguments can convert to, but only
3494 // if the operator we're looking at has built-in operator candidates
3495 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003496 Qualifiers VisibleTypeConversionsQuals;
3497 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003498 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3499 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3500
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003501 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003502 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3503 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003504 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003505 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003506 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003507 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003508 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003509 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003510 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003511 true,
3512 (Op == OO_Exclaim ||
3513 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003514 Op == OO_PipePipe),
3515 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003516 }
3517
3518 bool isComparison = false;
3519 switch (Op) {
3520 case OO_None:
3521 case NUM_OVERLOADED_OPERATORS:
3522 assert(false && "Expected an overloaded operator");
3523 break;
3524
Douglas Gregord08452f2008-11-19 15:42:04 +00003525 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003526 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003527 goto UnaryStar;
3528 else
3529 goto BinaryStar;
3530 break;
3531
3532 case OO_Plus: // '+' is either unary or binary
3533 if (NumArgs == 1)
3534 goto UnaryPlus;
3535 else
3536 goto BinaryPlus;
3537 break;
3538
3539 case OO_Minus: // '-' is either unary or binary
3540 if (NumArgs == 1)
3541 goto UnaryMinus;
3542 else
3543 goto BinaryMinus;
3544 break;
3545
3546 case OO_Amp: // '&' is either unary or binary
3547 if (NumArgs == 1)
3548 goto UnaryAmp;
3549 else
3550 goto BinaryAmp;
3551
3552 case OO_PlusPlus:
3553 case OO_MinusMinus:
3554 // C++ [over.built]p3:
3555 //
3556 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3557 // is either volatile or empty, there exist candidate operator
3558 // functions of the form
3559 //
3560 // VQ T& operator++(VQ T&);
3561 // T operator++(VQ T&, int);
3562 //
3563 // C++ [over.built]p4:
3564 //
3565 // For every pair (T, VQ), where T is an arithmetic type other
3566 // than bool, and VQ is either volatile or empty, there exist
3567 // candidate operator functions of the form
3568 //
3569 // VQ T& operator--(VQ T&);
3570 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003571 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003572 Arith < NumArithmeticTypes; ++Arith) {
3573 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003574 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003575 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003576
3577 // Non-volatile version.
3578 if (NumArgs == 1)
3579 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3580 else
3581 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003582 // heuristic to reduce number of builtin candidates in the set.
3583 // Add volatile version only if there are conversions to a volatile type.
3584 if (VisibleTypeConversionsQuals.hasVolatile()) {
3585 // Volatile version
3586 ParamTypes[0]
3587 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3588 if (NumArgs == 1)
3589 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3590 else
3591 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3592 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003593 }
3594
3595 // C++ [over.built]p5:
3596 //
3597 // For every pair (T, VQ), where T is a cv-qualified or
3598 // cv-unqualified object type, and VQ is either volatile or
3599 // empty, there exist candidate operator functions of the form
3600 //
3601 // T*VQ& operator++(T*VQ&);
3602 // T*VQ& operator--(T*VQ&);
3603 // T* operator++(T*VQ&, int);
3604 // T* operator--(T*VQ&, int);
3605 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3606 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3607 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003608 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003609 continue;
3610
Mike Stump11289f42009-09-09 15:08:12 +00003611 QualType ParamTypes[2] = {
3612 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003613 };
Mike Stump11289f42009-09-09 15:08:12 +00003614
Douglas Gregord08452f2008-11-19 15:42:04 +00003615 // Without volatile
3616 if (NumArgs == 1)
3617 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3618 else
3619 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3620
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003621 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3622 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003623 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003624 ParamTypes[0]
3625 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003626 if (NumArgs == 1)
3627 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3628 else
3629 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3630 }
3631 }
3632 break;
3633
3634 UnaryStar:
3635 // C++ [over.built]p6:
3636 // For every cv-qualified or cv-unqualified object type T, there
3637 // exist candidate operator functions of the form
3638 //
3639 // T& operator*(T*);
3640 //
3641 // C++ [over.built]p7:
3642 // For every function type T, there exist candidate operator
3643 // functions of the form
3644 // T& operator*(T*);
3645 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3646 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3647 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003648 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003649 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003650 &ParamTy, Args, 1, CandidateSet);
3651 }
3652 break;
3653
3654 UnaryPlus:
3655 // C++ [over.built]p8:
3656 // For every type T, there exist candidate operator functions of
3657 // the form
3658 //
3659 // T* operator+(T*);
3660 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3661 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3662 QualType ParamTy = *Ptr;
3663 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3664 }
Mike Stump11289f42009-09-09 15:08:12 +00003665
Douglas Gregord08452f2008-11-19 15:42:04 +00003666 // Fall through
3667
3668 UnaryMinus:
3669 // C++ [over.built]p9:
3670 // For every promoted arithmetic type T, there exist candidate
3671 // operator functions of the form
3672 //
3673 // T operator+(T);
3674 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003675 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003676 Arith < LastPromotedArithmeticType; ++Arith) {
3677 QualType ArithTy = ArithmeticTypes[Arith];
3678 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3679 }
3680 break;
3681
3682 case OO_Tilde:
3683 // C++ [over.built]p10:
3684 // For every promoted integral type T, there exist candidate
3685 // operator functions of the form
3686 //
3687 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003688 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003689 Int < LastPromotedIntegralType; ++Int) {
3690 QualType IntTy = ArithmeticTypes[Int];
3691 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3692 }
3693 break;
3694
Douglas Gregora11693b2008-11-12 17:17:38 +00003695 case OO_New:
3696 case OO_Delete:
3697 case OO_Array_New:
3698 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003699 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003700 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003701 break;
3702
3703 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003704 UnaryAmp:
3705 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003706 // C++ [over.match.oper]p3:
3707 // -- For the operator ',', the unary operator '&', or the
3708 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003709 break;
3710
Douglas Gregor84605ae2009-08-24 13:43:27 +00003711 case OO_EqualEqual:
3712 case OO_ExclaimEqual:
3713 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003714 // For every pointer to member type T, there exist candidate operator
3715 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003716 //
3717 // bool operator==(T,T);
3718 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003719 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003720 MemPtr = CandidateTypes.member_pointer_begin(),
3721 MemPtrEnd = CandidateTypes.member_pointer_end();
3722 MemPtr != MemPtrEnd;
3723 ++MemPtr) {
3724 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3725 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3726 }
Mike Stump11289f42009-09-09 15:08:12 +00003727
Douglas Gregor84605ae2009-08-24 13:43:27 +00003728 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003729
Douglas Gregora11693b2008-11-12 17:17:38 +00003730 case OO_Less:
3731 case OO_Greater:
3732 case OO_LessEqual:
3733 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003734 // C++ [over.built]p15:
3735 //
3736 // For every pointer or enumeration type T, there exist
3737 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003738 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003739 // bool operator<(T, T);
3740 // bool operator>(T, T);
3741 // bool operator<=(T, T);
3742 // bool operator>=(T, T);
3743 // bool operator==(T, T);
3744 // bool operator!=(T, T);
3745 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3746 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3747 QualType ParamTypes[2] = { *Ptr, *Ptr };
3748 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3749 }
Mike Stump11289f42009-09-09 15:08:12 +00003750 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003751 = CandidateTypes.enumeration_begin();
3752 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3753 QualType ParamTypes[2] = { *Enum, *Enum };
3754 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3755 }
3756
3757 // Fall through.
3758 isComparison = true;
3759
Douglas Gregord08452f2008-11-19 15:42:04 +00003760 BinaryPlus:
3761 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003762 if (!isComparison) {
3763 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3764
3765 // C++ [over.built]p13:
3766 //
3767 // For every cv-qualified or cv-unqualified object type T
3768 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003769 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003770 // T* operator+(T*, ptrdiff_t);
3771 // T& operator[](T*, ptrdiff_t); [BELOW]
3772 // T* operator-(T*, ptrdiff_t);
3773 // T* operator+(ptrdiff_t, T*);
3774 // T& operator[](ptrdiff_t, T*); [BELOW]
3775 //
3776 // C++ [over.built]p14:
3777 //
3778 // For every T, where T is a pointer to object type, there
3779 // exist candidate operator functions of the form
3780 //
3781 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003782 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003783 = CandidateTypes.pointer_begin();
3784 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3785 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3786
3787 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3788 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3789
3790 if (Op == OO_Plus) {
3791 // T* operator+(ptrdiff_t, T*);
3792 ParamTypes[0] = ParamTypes[1];
3793 ParamTypes[1] = *Ptr;
3794 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3795 } else {
3796 // ptrdiff_t operator-(T, T);
3797 ParamTypes[1] = *Ptr;
3798 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3799 Args, 2, CandidateSet);
3800 }
3801 }
3802 }
3803 // Fall through
3804
Douglas Gregora11693b2008-11-12 17:17:38 +00003805 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003806 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003807 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003808 // C++ [over.built]p12:
3809 //
3810 // For every pair of promoted arithmetic types L and R, there
3811 // exist candidate operator functions of the form
3812 //
3813 // LR operator*(L, R);
3814 // LR operator/(L, R);
3815 // LR operator+(L, R);
3816 // LR operator-(L, R);
3817 // bool operator<(L, R);
3818 // bool operator>(L, R);
3819 // bool operator<=(L, R);
3820 // bool operator>=(L, R);
3821 // bool operator==(L, R);
3822 // bool operator!=(L, R);
3823 //
3824 // where LR is the result of the usual arithmetic conversions
3825 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003826 //
3827 // C++ [over.built]p24:
3828 //
3829 // For every pair of promoted arithmetic types L and R, there exist
3830 // candidate operator functions of the form
3831 //
3832 // LR operator?(bool, L, R);
3833 //
3834 // where LR is the result of the usual arithmetic conversions
3835 // between types L and R.
3836 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003837 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003838 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003839 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003840 Right < LastPromotedArithmeticType; ++Right) {
3841 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003842 QualType Result
3843 = isComparison
3844 ? Context.BoolTy
3845 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003846 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3847 }
3848 }
3849 break;
3850
3851 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003852 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003853 case OO_Caret:
3854 case OO_Pipe:
3855 case OO_LessLess:
3856 case OO_GreaterGreater:
3857 // C++ [over.built]p17:
3858 //
3859 // For every pair of promoted integral types L and R, there
3860 // exist candidate operator functions of the form
3861 //
3862 // LR operator%(L, R);
3863 // LR operator&(L, R);
3864 // LR operator^(L, R);
3865 // LR operator|(L, R);
3866 // L operator<<(L, R);
3867 // L operator>>(L, R);
3868 //
3869 // where LR is the result of the usual arithmetic conversions
3870 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003871 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003872 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003873 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003874 Right < LastPromotedIntegralType; ++Right) {
3875 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3876 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3877 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003878 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003879 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3880 }
3881 }
3882 break;
3883
3884 case OO_Equal:
3885 // C++ [over.built]p20:
3886 //
3887 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003888 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003889 // empty, there exist candidate operator functions of the form
3890 //
3891 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003892 for (BuiltinCandidateTypeSet::iterator
3893 Enum = CandidateTypes.enumeration_begin(),
3894 EnumEnd = CandidateTypes.enumeration_end();
3895 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003896 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003897 CandidateSet);
3898 for (BuiltinCandidateTypeSet::iterator
3899 MemPtr = CandidateTypes.member_pointer_begin(),
3900 MemPtrEnd = CandidateTypes.member_pointer_end();
3901 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003902 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003903 CandidateSet);
3904 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003905
3906 case OO_PlusEqual:
3907 case OO_MinusEqual:
3908 // C++ [over.built]p19:
3909 //
3910 // For every pair (T, VQ), where T is any type and VQ is either
3911 // volatile or empty, there exist candidate operator functions
3912 // of the form
3913 //
3914 // T*VQ& operator=(T*VQ&, T*);
3915 //
3916 // C++ [over.built]p21:
3917 //
3918 // For every pair (T, VQ), where T is a cv-qualified or
3919 // cv-unqualified object type and VQ is either volatile or
3920 // empty, there exist candidate operator functions of the form
3921 //
3922 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3923 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3924 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3925 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3926 QualType ParamTypes[2];
3927 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3928
3929 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003930 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3932 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003933
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003934 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3935 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003936 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003937 ParamTypes[0]
3938 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003939 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3940 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003941 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003942 }
3943 // Fall through.
3944
3945 case OO_StarEqual:
3946 case OO_SlashEqual:
3947 // C++ [over.built]p18:
3948 //
3949 // For every triple (L, VQ, R), where L is an arithmetic type,
3950 // VQ is either volatile or empty, and R is a promoted
3951 // arithmetic type, there exist candidate operator functions of
3952 // the form
3953 //
3954 // VQ L& operator=(VQ L&, R);
3955 // VQ L& operator*=(VQ L&, R);
3956 // VQ L& operator/=(VQ L&, R);
3957 // VQ L& operator+=(VQ L&, R);
3958 // VQ L& operator-=(VQ L&, R);
3959 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003960 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003961 Right < LastPromotedArithmeticType; ++Right) {
3962 QualType ParamTypes[2];
3963 ParamTypes[1] = ArithmeticTypes[Right];
3964
3965 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003966 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003967 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3968 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003969
3970 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003971 if (VisibleTypeConversionsQuals.hasVolatile()) {
3972 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3973 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3974 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3975 /*IsAssigmentOperator=*/Op == OO_Equal);
3976 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003977 }
3978 }
3979 break;
3980
3981 case OO_PercentEqual:
3982 case OO_LessLessEqual:
3983 case OO_GreaterGreaterEqual:
3984 case OO_AmpEqual:
3985 case OO_CaretEqual:
3986 case OO_PipeEqual:
3987 // C++ [over.built]p22:
3988 //
3989 // For every triple (L, VQ, R), where L is an integral type, VQ
3990 // is either volatile or empty, and R is a promoted integral
3991 // type, there exist candidate operator functions of the form
3992 //
3993 // VQ L& operator%=(VQ L&, R);
3994 // VQ L& operator<<=(VQ L&, R);
3995 // VQ L& operator>>=(VQ L&, R);
3996 // VQ L& operator&=(VQ L&, R);
3997 // VQ L& operator^=(VQ L&, R);
3998 // VQ L& operator|=(VQ L&, R);
3999 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004000 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004001 Right < LastPromotedIntegralType; ++Right) {
4002 QualType ParamTypes[2];
4003 ParamTypes[1] = ArithmeticTypes[Right];
4004
4005 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004006 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004007 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004008 if (VisibleTypeConversionsQuals.hasVolatile()) {
4009 // Add this built-in operator as a candidate (VQ is 'volatile').
4010 ParamTypes[0] = ArithmeticTypes[Left];
4011 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4012 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4013 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4014 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004015 }
4016 }
4017 break;
4018
Douglas Gregord08452f2008-11-19 15:42:04 +00004019 case OO_Exclaim: {
4020 // C++ [over.operator]p23:
4021 //
4022 // There also exist candidate operator functions of the form
4023 //
Mike Stump11289f42009-09-09 15:08:12 +00004024 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004025 // bool operator&&(bool, bool); [BELOW]
4026 // bool operator||(bool, bool); [BELOW]
4027 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004028 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4029 /*IsAssignmentOperator=*/false,
4030 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004031 break;
4032 }
4033
Douglas Gregora11693b2008-11-12 17:17:38 +00004034 case OO_AmpAmp:
4035 case OO_PipePipe: {
4036 // C++ [over.operator]p23:
4037 //
4038 // There also exist candidate operator functions of the form
4039 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004040 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004041 // bool operator&&(bool, bool);
4042 // bool operator||(bool, bool);
4043 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004044 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4045 /*IsAssignmentOperator=*/false,
4046 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004047 break;
4048 }
4049
4050 case OO_Subscript:
4051 // C++ [over.built]p13:
4052 //
4053 // For every cv-qualified or cv-unqualified object type T there
4054 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004055 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004056 // T* operator+(T*, ptrdiff_t); [ABOVE]
4057 // T& operator[](T*, ptrdiff_t);
4058 // T* operator-(T*, ptrdiff_t); [ABOVE]
4059 // T* operator+(ptrdiff_t, T*); [ABOVE]
4060 // T& operator[](ptrdiff_t, T*);
4061 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4062 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4063 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004064 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004065 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004066
4067 // T& operator[](T*, ptrdiff_t)
4068 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4069
4070 // T& operator[](ptrdiff_t, T*);
4071 ParamTypes[0] = ParamTypes[1];
4072 ParamTypes[1] = *Ptr;
4073 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4074 }
4075 break;
4076
4077 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004078 // C++ [over.built]p11:
4079 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4080 // C1 is the same type as C2 or is a derived class of C2, T is an object
4081 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4082 // there exist candidate operator functions of the form
4083 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4084 // where CV12 is the union of CV1 and CV2.
4085 {
4086 for (BuiltinCandidateTypeSet::iterator Ptr =
4087 CandidateTypes.pointer_begin();
4088 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4089 QualType C1Ty = (*Ptr);
4090 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004091 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004092 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004093 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004094 if (!isa<RecordType>(C1))
4095 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004096 // heuristic to reduce number of builtin candidates in the set.
4097 // Add volatile/restrict version only if there are conversions to a
4098 // volatile/restrict type.
4099 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4100 continue;
4101 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4102 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004103 }
4104 for (BuiltinCandidateTypeSet::iterator
4105 MemPtr = CandidateTypes.member_pointer_begin(),
4106 MemPtrEnd = CandidateTypes.member_pointer_end();
4107 MemPtr != MemPtrEnd; ++MemPtr) {
4108 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4109 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004110 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004111 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4112 break;
4113 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4114 // build CV12 T&
4115 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004116 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4117 T.isVolatileQualified())
4118 continue;
4119 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4120 T.isRestrictQualified())
4121 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004122 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004123 QualType ResultTy = Context.getLValueReferenceType(T);
4124 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4125 }
4126 }
4127 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004128 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004129
4130 case OO_Conditional:
4131 // Note that we don't consider the first argument, since it has been
4132 // contextually converted to bool long ago. The candidates below are
4133 // therefore added as binary.
4134 //
4135 // C++ [over.built]p24:
4136 // For every type T, where T is a pointer or pointer-to-member type,
4137 // there exist candidate operator functions of the form
4138 //
4139 // T operator?(bool, T, T);
4140 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004141 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4142 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4143 QualType ParamTypes[2] = { *Ptr, *Ptr };
4144 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4145 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004146 for (BuiltinCandidateTypeSet::iterator Ptr =
4147 CandidateTypes.member_pointer_begin(),
4148 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4149 QualType ParamTypes[2] = { *Ptr, *Ptr };
4150 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4151 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004152 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004153 }
4154}
4155
Douglas Gregore254f902009-02-04 00:32:51 +00004156/// \brief Add function candidates found via argument-dependent lookup
4157/// to the set of overloading candidates.
4158///
4159/// This routine performs argument-dependent name lookup based on the
4160/// given function name (which may also be an operator name) and adds
4161/// all of the overload candidates found by ADL to the overload
4162/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004163void
Douglas Gregore254f902009-02-04 00:32:51 +00004164Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004165 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004166 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004167 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004168 OverloadCandidateSet& CandidateSet,
4169 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004170 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004171
John McCall91f61fc2010-01-26 06:04:06 +00004172 // FIXME: This approach for uniquing ADL results (and removing
4173 // redundant candidates from the set) relies on pointer-equality,
4174 // which means we need to key off the canonical decl. However,
4175 // always going back to the canonical decl might not get us the
4176 // right set of default arguments. What default arguments are
4177 // we supposed to consider on ADL candidates, anyway?
4178
Douglas Gregorcabea402009-09-22 15:41:20 +00004179 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004180 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004181
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004182 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004183 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4184 CandEnd = CandidateSet.end();
4185 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004186 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004187 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004188 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004189 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004190 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004191
4192 // For each of the ADL candidates we found, add it to the overload
4193 // set.
John McCall8fe68082010-01-26 07:16:45 +00004194 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00004195 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004196 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004197 continue;
4198
John McCallb89836b2010-01-26 01:37:31 +00004199 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004200 false, false, PartialOverloading);
4201 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004202 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCallb89836b2010-01-26 01:37:31 +00004203 AS_none, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004204 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004205 }
Douglas Gregore254f902009-02-04 00:32:51 +00004206}
4207
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004208/// isBetterOverloadCandidate - Determines whether the first overload
4209/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004210bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004211Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004212 const OverloadCandidate& Cand2,
4213 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004214 // Define viable functions to be better candidates than non-viable
4215 // functions.
4216 if (!Cand2.Viable)
4217 return Cand1.Viable;
4218 else if (!Cand1.Viable)
4219 return false;
4220
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004221 // C++ [over.match.best]p1:
4222 //
4223 // -- if F is a static member function, ICS1(F) is defined such
4224 // that ICS1(F) is neither better nor worse than ICS1(G) for
4225 // any function G, and, symmetrically, ICS1(G) is neither
4226 // better nor worse than ICS1(F).
4227 unsigned StartArg = 0;
4228 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4229 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004230
Douglas Gregord3cb3562009-07-07 23:38:56 +00004231 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004232 // A viable function F1 is defined to be a better function than another
4233 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004234 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004235 unsigned NumArgs = Cand1.Conversions.size();
4236 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4237 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004238 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004239 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4240 Cand2.Conversions[ArgIdx])) {
4241 case ImplicitConversionSequence::Better:
4242 // Cand1 has a better conversion sequence.
4243 HasBetterConversion = true;
4244 break;
4245
4246 case ImplicitConversionSequence::Worse:
4247 // Cand1 can't be better than Cand2.
4248 return false;
4249
4250 case ImplicitConversionSequence::Indistinguishable:
4251 // Do nothing.
4252 break;
4253 }
4254 }
4255
Mike Stump11289f42009-09-09 15:08:12 +00004256 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004257 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004258 if (HasBetterConversion)
4259 return true;
4260
Mike Stump11289f42009-09-09 15:08:12 +00004261 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004262 // specialization, or, if not that,
4263 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4264 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4265 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004266
4267 // -- F1 and F2 are function template specializations, and the function
4268 // template for F1 is more specialized than the template for F2
4269 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004270 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004271 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4272 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004273 if (FunctionTemplateDecl *BetterTemplate
4274 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4275 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004276 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004277 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4278 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004279 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004280
Douglas Gregora1f013e2008-11-07 22:36:19 +00004281 // -- the context is an initialization by user-defined conversion
4282 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4283 // from the return type of F1 to the destination type (i.e.,
4284 // the type of the entity being initialized) is a better
4285 // conversion sequence than the standard conversion sequence
4286 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004287 if (Cand1.Function && Cand2.Function &&
4288 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004289 isa<CXXConversionDecl>(Cand2.Function)) {
4290 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4291 Cand2.FinalConversion)) {
4292 case ImplicitConversionSequence::Better:
4293 // Cand1 has a better conversion sequence.
4294 return true;
4295
4296 case ImplicitConversionSequence::Worse:
4297 // Cand1 can't be better than Cand2.
4298 return false;
4299
4300 case ImplicitConversionSequence::Indistinguishable:
4301 // Do nothing
4302 break;
4303 }
4304 }
4305
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004306 return false;
4307}
4308
Mike Stump11289f42009-09-09 15:08:12 +00004309/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004310/// within an overload candidate set.
4311///
4312/// \param CandidateSet the set of candidate functions.
4313///
4314/// \param Loc the location of the function name (or operator symbol) for
4315/// which overload resolution occurs.
4316///
Mike Stump11289f42009-09-09 15:08:12 +00004317/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004318/// function, Best points to the candidate function found.
4319///
4320/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004321OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4322 SourceLocation Loc,
4323 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004324 // Find the best viable function.
4325 Best = CandidateSet.end();
4326 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4327 Cand != CandidateSet.end(); ++Cand) {
4328 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004329 if (Best == CandidateSet.end() ||
4330 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004331 Best = Cand;
4332 }
4333 }
4334
4335 // If we didn't find any viable functions, abort.
4336 if (Best == CandidateSet.end())
4337 return OR_No_Viable_Function;
4338
4339 // Make sure that this function is better than every other viable
4340 // function. If not, we have an ambiguity.
4341 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4342 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004343 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004344 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004345 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004346 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004347 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004348 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004349 }
Mike Stump11289f42009-09-09 15:08:12 +00004350
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004351 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004352 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004353 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004354 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004355 return OR_Deleted;
4356
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004357 // C++ [basic.def.odr]p2:
4358 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004359 // when referred to from a potentially-evaluated expression. [Note: this
4360 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004361 // (clause 13), user-defined conversions (12.3.2), allocation function for
4362 // placement new (5.3.4), as well as non-default initialization (8.5).
4363 if (Best->Function)
4364 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004365 return OR_Success;
4366}
4367
John McCall53262c92010-01-12 02:15:36 +00004368namespace {
4369
4370enum OverloadCandidateKind {
4371 oc_function,
4372 oc_method,
4373 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004374 oc_function_template,
4375 oc_method_template,
4376 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004377 oc_implicit_default_constructor,
4378 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004379 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004380};
4381
John McCalle1ac8d12010-01-13 00:25:19 +00004382OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4383 FunctionDecl *Fn,
4384 std::string &Description) {
4385 bool isTemplate = false;
4386
4387 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4388 isTemplate = true;
4389 Description = S.getTemplateArgumentBindingsText(
4390 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4391 }
John McCallfd0b2f82010-01-06 09:43:14 +00004392
4393 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004394 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004395 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004396
John McCall53262c92010-01-12 02:15:36 +00004397 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4398 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004399 }
4400
4401 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4402 // This actually gets spelled 'candidate function' for now, but
4403 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004404 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004405 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004406
4407 assert(Meth->isCopyAssignment()
4408 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004409 return oc_implicit_copy_assignment;
4410 }
4411
John McCalle1ac8d12010-01-13 00:25:19 +00004412 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004413}
4414
4415} // end anonymous namespace
4416
4417// Notes the location of an overload candidate.
4418void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004419 std::string FnDesc;
4420 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4421 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4422 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004423}
4424
John McCall0d1da222010-01-12 00:44:57 +00004425/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4426/// "lead" diagnostic; it will be given two arguments, the source and
4427/// target types of the conversion.
4428void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4429 SourceLocation CaretLoc,
4430 const PartialDiagnostic &PDiag) {
4431 Diag(CaretLoc, PDiag)
4432 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4433 for (AmbiguousConversionSequence::const_iterator
4434 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4435 NoteOverloadCandidate(*I);
4436 }
John McCall12f97bc2010-01-08 04:41:39 +00004437}
4438
John McCall0d1da222010-01-12 00:44:57 +00004439namespace {
4440
John McCall6a61b522010-01-13 09:16:55 +00004441void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4442 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4443 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004444 assert(Cand->Function && "for now, candidate must be a function");
4445 FunctionDecl *Fn = Cand->Function;
4446
4447 // There's a conversion slot for the object argument if this is a
4448 // non-constructor method. Note that 'I' corresponds the
4449 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004450 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004451 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004452 if (I == 0)
4453 isObjectArgument = true;
4454 else
4455 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004456 }
4457
John McCalle1ac8d12010-01-13 00:25:19 +00004458 std::string FnDesc;
4459 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4460
John McCall6a61b522010-01-13 09:16:55 +00004461 Expr *FromExpr = Conv.Bad.FromExpr;
4462 QualType FromTy = Conv.Bad.getFromType();
4463 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004464
John McCallfb7ad0f2010-02-02 02:42:52 +00004465 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004466 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004467 Expr *E = FromExpr->IgnoreParens();
4468 if (isa<UnaryOperator>(E))
4469 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004470 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004471
4472 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4473 << (unsigned) FnKind << FnDesc
4474 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4475 << ToTy << Name << I+1;
4476 return;
4477 }
4478
John McCall6d174642010-01-23 08:10:49 +00004479 // Do some hand-waving analysis to see if the non-viability is due
4480 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004481 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4482 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4483 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4484 CToTy = RT->getPointeeType();
4485 else {
4486 // TODO: detect and diagnose the full richness of const mismatches.
4487 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4488 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4489 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4490 }
4491
4492 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4493 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4494 // It is dumb that we have to do this here.
4495 while (isa<ArrayType>(CFromTy))
4496 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4497 while (isa<ArrayType>(CToTy))
4498 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4499
4500 Qualifiers FromQs = CFromTy.getQualifiers();
4501 Qualifiers ToQs = CToTy.getQualifiers();
4502
4503 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4504 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4505 << (unsigned) FnKind << FnDesc
4506 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4507 << FromTy
4508 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4509 << (unsigned) isObjectArgument << I+1;
4510 return;
4511 }
4512
4513 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4514 assert(CVR && "unexpected qualifiers mismatch");
4515
4516 if (isObjectArgument) {
4517 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4518 << (unsigned) FnKind << FnDesc
4519 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4520 << FromTy << (CVR - 1);
4521 } else {
4522 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4523 << (unsigned) FnKind << FnDesc
4524 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4525 << FromTy << (CVR - 1) << I+1;
4526 }
4527 return;
4528 }
4529
John McCall6d174642010-01-23 08:10:49 +00004530 // Diagnose references or pointers to incomplete types differently,
4531 // since it's far from impossible that the incompleteness triggered
4532 // the failure.
4533 QualType TempFromTy = FromTy.getNonReferenceType();
4534 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4535 TempFromTy = PTy->getPointeeType();
4536 if (TempFromTy->isIncompleteType()) {
4537 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4538 << (unsigned) FnKind << FnDesc
4539 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4540 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4541 return;
4542 }
4543
John McCall47000992010-01-14 03:28:57 +00004544 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4546 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004548 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004549}
4550
4551void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4552 unsigned NumFormalArgs) {
4553 // TODO: treat calls to a missing default constructor as a special case
4554
4555 FunctionDecl *Fn = Cand->Function;
4556 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4557
4558 unsigned MinParams = Fn->getMinRequiredArguments();
4559
4560 // at least / at most / exactly
4561 unsigned mode, modeCount;
4562 if (NumFormalArgs < MinParams) {
4563 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4564 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4565 mode = 0; // "at least"
4566 else
4567 mode = 2; // "exactly"
4568 modeCount = MinParams;
4569 } else {
4570 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4571 if (MinParams != FnTy->getNumArgs())
4572 mode = 1; // "at most"
4573 else
4574 mode = 2; // "exactly"
4575 modeCount = FnTy->getNumArgs();
4576 }
4577
4578 std::string Description;
4579 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4580
4581 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4582 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004583}
4584
John McCall8b9ed552010-02-01 18:53:26 +00004585/// Diagnose a failed template-argument deduction.
4586void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4587 Expr **Args, unsigned NumArgs) {
4588 FunctionDecl *Fn = Cand->Function; // pattern
4589
4590 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4591 Cand->DeductionFailure.TemplateParameter);
4592
4593 switch (Cand->DeductionFailure.Result) {
4594 case Sema::TDK_Success:
4595 llvm_unreachable("TDK_success while diagnosing bad deduction");
4596
4597 case Sema::TDK_Incomplete: {
4598 NamedDecl *ParamD;
4599 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4600 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4601 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4602 assert(ParamD && "no parameter found for incomplete deduction result");
4603 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4604 << ParamD->getDeclName();
4605 return;
4606 }
4607
4608 // TODO: diagnose these individually, then kill off
4609 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4610 case Sema::TDK_InstantiationDepth:
4611 case Sema::TDK_Inconsistent:
4612 case Sema::TDK_InconsistentQuals:
4613 case Sema::TDK_SubstitutionFailure:
4614 case Sema::TDK_NonDeducedMismatch:
4615 case Sema::TDK_TooManyArguments:
4616 case Sema::TDK_TooFewArguments:
4617 case Sema::TDK_InvalidExplicitArguments:
4618 case Sema::TDK_FailedOverloadResolution:
4619 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4620 return;
4621 }
4622}
4623
4624/// Generates a 'note' diagnostic for an overload candidate. We've
4625/// already generated a primary error at the call site.
4626///
4627/// It really does need to be a single diagnostic with its caret
4628/// pointed at the candidate declaration. Yes, this creates some
4629/// major challenges of technical writing. Yes, this makes pointing
4630/// out problems with specific arguments quite awkward. It's still
4631/// better than generating twenty screens of text for every failed
4632/// overload.
4633///
4634/// It would be great to be able to express per-candidate problems
4635/// more richly for those diagnostic clients that cared, but we'd
4636/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004637void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4638 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004639 FunctionDecl *Fn = Cand->Function;
4640
John McCall12f97bc2010-01-08 04:41:39 +00004641 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004642 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004643 std::string FnDesc;
4644 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004645
4646 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004647 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004648 return;
John McCall12f97bc2010-01-08 04:41:39 +00004649 }
4650
John McCalle1ac8d12010-01-13 00:25:19 +00004651 // We don't really have anything else to say about viable candidates.
4652 if (Cand->Viable) {
4653 S.NoteOverloadCandidate(Fn);
4654 return;
4655 }
John McCall0d1da222010-01-12 00:44:57 +00004656
John McCall6a61b522010-01-13 09:16:55 +00004657 switch (Cand->FailureKind) {
4658 case ovl_fail_too_many_arguments:
4659 case ovl_fail_too_few_arguments:
4660 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004661
John McCall6a61b522010-01-13 09:16:55 +00004662 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004663 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4664
John McCallfe796dd2010-01-23 05:17:32 +00004665 case ovl_fail_trivial_conversion:
4666 case ovl_fail_bad_final_conversion:
John McCall6a61b522010-01-13 09:16:55 +00004667 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004668
John McCall65eb8792010-02-25 01:37:24 +00004669 case ovl_fail_bad_conversion: {
4670 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4671 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00004672 if (Cand->Conversions[I].isBad())
4673 return DiagnoseBadConversion(S, Cand, I);
4674
4675 // FIXME: this currently happens when we're called from SemaInit
4676 // when user-conversion overload fails. Figure out how to handle
4677 // those conditions and diagnose them well.
4678 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004679 }
John McCall65eb8792010-02-25 01:37:24 +00004680 }
John McCalld3224162010-01-08 00:58:21 +00004681}
4682
4683void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4684 // Desugar the type of the surrogate down to a function type,
4685 // retaining as many typedefs as possible while still showing
4686 // the function type (and, therefore, its parameter types).
4687 QualType FnType = Cand->Surrogate->getConversionType();
4688 bool isLValueReference = false;
4689 bool isRValueReference = false;
4690 bool isPointer = false;
4691 if (const LValueReferenceType *FnTypeRef =
4692 FnType->getAs<LValueReferenceType>()) {
4693 FnType = FnTypeRef->getPointeeType();
4694 isLValueReference = true;
4695 } else if (const RValueReferenceType *FnTypeRef =
4696 FnType->getAs<RValueReferenceType>()) {
4697 FnType = FnTypeRef->getPointeeType();
4698 isRValueReference = true;
4699 }
4700 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4701 FnType = FnTypePtr->getPointeeType();
4702 isPointer = true;
4703 }
4704 // Desugar down to a function type.
4705 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4706 // Reconstruct the pointer/reference as appropriate.
4707 if (isPointer) FnType = S.Context.getPointerType(FnType);
4708 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4709 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4710
4711 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4712 << FnType;
4713}
4714
4715void NoteBuiltinOperatorCandidate(Sema &S,
4716 const char *Opc,
4717 SourceLocation OpLoc,
4718 OverloadCandidate *Cand) {
4719 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4720 std::string TypeStr("operator");
4721 TypeStr += Opc;
4722 TypeStr += "(";
4723 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4724 if (Cand->Conversions.size() == 1) {
4725 TypeStr += ")";
4726 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4727 } else {
4728 TypeStr += ", ";
4729 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4730 TypeStr += ")";
4731 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4732 }
4733}
4734
4735void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4736 OverloadCandidate *Cand) {
4737 unsigned NoOperands = Cand->Conversions.size();
4738 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4739 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004740 if (ICS.isBad()) break; // all meaningless after first invalid
4741 if (!ICS.isAmbiguous()) continue;
4742
4743 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4744 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004745 }
4746}
4747
John McCall3712d9e2010-01-15 23:32:50 +00004748SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4749 if (Cand->Function)
4750 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00004751 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00004752 return Cand->Surrogate->getLocation();
4753 return SourceLocation();
4754}
4755
John McCallad2587a2010-01-12 00:48:53 +00004756struct CompareOverloadCandidatesForDisplay {
4757 Sema &S;
4758 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004759
4760 bool operator()(const OverloadCandidate *L,
4761 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00004762 // Fast-path this check.
4763 if (L == R) return false;
4764
John McCall12f97bc2010-01-08 04:41:39 +00004765 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004766 if (L->Viable) {
4767 if (!R->Viable) return true;
4768
4769 // TODO: introduce a tri-valued comparison for overload
4770 // candidates. Would be more worthwhile if we had a sort
4771 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00004772 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4773 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00004774 } else if (R->Viable)
4775 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004776
John McCall3712d9e2010-01-15 23:32:50 +00004777 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004778
John McCall3712d9e2010-01-15 23:32:50 +00004779 // Criteria by which we can sort non-viable candidates:
4780 if (!L->Viable) {
4781 // 1. Arity mismatches come after other candidates.
4782 if (L->FailureKind == ovl_fail_too_many_arguments ||
4783 L->FailureKind == ovl_fail_too_few_arguments)
4784 return false;
4785 if (R->FailureKind == ovl_fail_too_many_arguments ||
4786 R->FailureKind == ovl_fail_too_few_arguments)
4787 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004788
John McCallfe796dd2010-01-23 05:17:32 +00004789 // 2. Bad conversions come first and are ordered by the number
4790 // of bad conversions and quality of good conversions.
4791 if (L->FailureKind == ovl_fail_bad_conversion) {
4792 if (R->FailureKind != ovl_fail_bad_conversion)
4793 return true;
4794
4795 // If there's any ordering between the defined conversions...
4796 // FIXME: this might not be transitive.
4797 assert(L->Conversions.size() == R->Conversions.size());
4798
4799 int leftBetter = 0;
4800 for (unsigned I = 0, E = L->Conversions.size(); I != E; ++I) {
4801 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4802 R->Conversions[I])) {
4803 case ImplicitConversionSequence::Better:
4804 leftBetter++;
4805 break;
4806
4807 case ImplicitConversionSequence::Worse:
4808 leftBetter--;
4809 break;
4810
4811 case ImplicitConversionSequence::Indistinguishable:
4812 break;
4813 }
4814 }
4815 if (leftBetter > 0) return true;
4816 if (leftBetter < 0) return false;
4817
4818 } else if (R->FailureKind == ovl_fail_bad_conversion)
4819 return false;
4820
John McCall3712d9e2010-01-15 23:32:50 +00004821 // TODO: others?
4822 }
4823
4824 // Sort everything else by location.
4825 SourceLocation LLoc = GetLocationForCandidate(L);
4826 SourceLocation RLoc = GetLocationForCandidate(R);
4827
4828 // Put candidates without locations (e.g. builtins) at the end.
4829 if (LLoc.isInvalid()) return false;
4830 if (RLoc.isInvalid()) return true;
4831
4832 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004833 }
4834};
4835
John McCallfe796dd2010-01-23 05:17:32 +00004836/// CompleteNonViableCandidate - Normally, overload resolution only
4837/// computes up to the first
4838void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4839 Expr **Args, unsigned NumArgs) {
4840 assert(!Cand->Viable);
4841
4842 // Don't do anything on failures other than bad conversion.
4843 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4844
4845 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00004846 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00004847 unsigned ConvCount = Cand->Conversions.size();
4848 while (true) {
4849 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4850 ConvIdx++;
4851 if (Cand->Conversions[ConvIdx - 1].isBad())
4852 break;
4853 }
4854
4855 if (ConvIdx == ConvCount)
4856 return;
4857
John McCall65eb8792010-02-25 01:37:24 +00004858 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
4859 "remaining conversion is initialized?");
4860
John McCallfe796dd2010-01-23 05:17:32 +00004861 // FIXME: these should probably be preserved from the overload
4862 // operation somehow.
4863 bool SuppressUserConversions = false;
4864 bool ForceRValue = false;
4865
4866 const FunctionProtoType* Proto;
4867 unsigned ArgIdx = ConvIdx;
4868
4869 if (Cand->IsSurrogate) {
4870 QualType ConvType
4871 = Cand->Surrogate->getConversionType().getNonReferenceType();
4872 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4873 ConvType = ConvPtrType->getPointeeType();
4874 Proto = ConvType->getAs<FunctionProtoType>();
4875 ArgIdx--;
4876 } else if (Cand->Function) {
4877 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4878 if (isa<CXXMethodDecl>(Cand->Function) &&
4879 !isa<CXXConstructorDecl>(Cand->Function))
4880 ArgIdx--;
4881 } else {
4882 // Builtin binary operator with a bad first conversion.
4883 assert(ConvCount <= 3);
4884 for (; ConvIdx != ConvCount; ++ConvIdx)
4885 Cand->Conversions[ConvIdx]
4886 = S.TryCopyInitialization(Args[ConvIdx],
4887 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4888 SuppressUserConversions, ForceRValue,
4889 /*InOverloadResolution*/ true);
4890 return;
4891 }
4892
4893 // Fill in the rest of the conversions.
4894 unsigned NumArgsInProto = Proto->getNumArgs();
4895 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4896 if (ArgIdx < NumArgsInProto)
4897 Cand->Conversions[ConvIdx]
4898 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4899 SuppressUserConversions, ForceRValue,
4900 /*InOverloadResolution=*/true);
4901 else
4902 Cand->Conversions[ConvIdx].setEllipsis();
4903 }
4904}
4905
John McCalld3224162010-01-08 00:58:21 +00004906} // end anonymous namespace
4907
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004908/// PrintOverloadCandidates - When overload resolution fails, prints
4909/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004910/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004911void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004912Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004913 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004914 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004915 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004916 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004917 // Sort the candidates by viability and position. Sorting directly would
4918 // be prohibitive, so we make a set of pointers and sort those.
4919 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4920 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4921 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4922 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00004923 Cand != LastCand; ++Cand) {
4924 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00004925 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00004926 else if (OCD == OCD_AllCandidates) {
4927 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4928 Cands.push_back(Cand);
4929 }
4930 }
4931
John McCallad2587a2010-01-12 00:48:53 +00004932 std::sort(Cands.begin(), Cands.end(),
4933 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004934
John McCall0d1da222010-01-12 00:44:57 +00004935 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004936
John McCall12f97bc2010-01-08 04:41:39 +00004937 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4938 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4939 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004940
John McCalld3224162010-01-08 00:58:21 +00004941 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004942 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004943 else if (Cand->IsSurrogate)
4944 NoteSurrogateCandidate(*this, Cand);
4945
4946 // This a builtin candidate. We do not, in general, want to list
4947 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004948 else if (Cand->Viable) {
4949 // Generally we only see ambiguities including viable builtin
4950 // operators if overload resolution got screwed up by an
4951 // ambiguous user-defined conversion.
4952 //
4953 // FIXME: It's quite possible for different conversions to see
4954 // different ambiguities, though.
4955 if (!ReportedAmbiguousConversions) {
4956 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4957 ReportedAmbiguousConversions = true;
4958 }
John McCalld3224162010-01-08 00:58:21 +00004959
John McCall0d1da222010-01-12 00:44:57 +00004960 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004961 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004962 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004963 }
4964}
4965
John McCall1acbbb52010-02-02 06:20:04 +00004966static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, NamedDecl *D,
John McCall58cc69d2010-01-27 01:50:18 +00004967 AccessSpecifier AS) {
4968 if (isa<UnresolvedLookupExpr>(E))
4969 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D, AS);
4970
4971 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D, AS);
4972}
4973
Douglas Gregorcd695e52008-11-10 20:40:00 +00004974/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4975/// an overloaded function (C++ [over.over]), where @p From is an
4976/// expression with overloaded function type and @p ToType is the type
4977/// we're trying to resolve to. For example:
4978///
4979/// @code
4980/// int f(double);
4981/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004982///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004983/// int (*pfd)(double) = f; // selects f(double)
4984/// @endcode
4985///
4986/// This routine returns the resulting FunctionDecl if it could be
4987/// resolved, and NULL otherwise. When @p Complain is true, this
4988/// routine will emit diagnostics if there is an error.
4989FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004990Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004991 bool Complain) {
4992 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004993 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004994 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004995 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004996 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004997 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004998 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004999 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005000 FunctionType = MemTypePtr->getPointeeType();
5001 IsMember = true;
5002 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005003
5004 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00005005 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00005006 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005007 return 0;
5008
5009 // Find the actual overloaded function declaration.
John McCall1acbbb52010-02-02 06:20:04 +00005010 if (From->getType() != Context.OverloadTy)
5011 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005012
Douglas Gregorcd695e52008-11-10 20:40:00 +00005013 // C++ [over.over]p1:
5014 // [...] [Note: any redundant set of parentheses surrounding the
5015 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005016 // C++ [over.over]p1:
5017 // [...] The overloaded function name can be preceded by the &
5018 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005019 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5020 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5021 if (OvlExpr->hasExplicitTemplateArgs()) {
5022 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5023 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005024 }
5025
Douglas Gregorcd695e52008-11-10 20:40:00 +00005026 // Look through all of the overloaded functions, searching for one
5027 // whose type matches exactly.
John McCall58cc69d2010-01-27 01:50:18 +00005028 UnresolvedSet<4> Matches; // contains only FunctionDecls
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005029 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005030 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5031 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005032 // Look through any using declarations to find the underlying function.
5033 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5034
Douglas Gregorcd695e52008-11-10 20:40:00 +00005035 // C++ [over.over]p3:
5036 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005037 // targets of type "pointer-to-function" or "reference-to-function."
5038 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005039 // type "pointer-to-member-function."
5040 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005041
Mike Stump11289f42009-09-09 15:08:12 +00005042 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005043 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005044 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005045 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005046 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005047 // static when converting to member pointer.
5048 if (Method->isStatic() == IsMember)
5049 continue;
5050 } else if (IsMember)
5051 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005052
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005053 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005054 // If the name is a function template, template argument deduction is
5055 // done (14.8.2.2), and if the argument deduction succeeds, the
5056 // resulting template argument list is used to generate a single
5057 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005058 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005059 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005060 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005061 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005062 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005063 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005064 FunctionType, Specialization, Info)) {
5065 // FIXME: make a note of the failed deduction for diagnostics.
5066 (void)Result;
5067 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005068 // FIXME: If the match isn't exact, shouldn't we just drop this as
5069 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005070 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005071 == Context.getCanonicalType(Specialization->getType()));
John McCall58cc69d2010-01-27 01:50:18 +00005072 Matches.addDecl(cast<FunctionDecl>(Specialization->getCanonicalDecl()),
5073 I.getAccess());
Douglas Gregor9b146582009-07-08 20:55:45 +00005074 }
John McCalld14a8642009-11-21 08:51:07 +00005075
5076 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005077 }
Mike Stump11289f42009-09-09 15:08:12 +00005078
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005079 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005080 // Skip non-static functions when converting to pointer, and static
5081 // when converting to member pointer.
5082 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005083 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005084
5085 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005086 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005087 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005088 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005089 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005090
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005091 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005092 QualType ResultTy;
5093 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5094 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5095 ResultTy)) {
John McCall58cc69d2010-01-27 01:50:18 +00005096 Matches.addDecl(cast<FunctionDecl>(FunDecl->getCanonicalDecl()),
5097 I.getAccess());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005098 FoundNonTemplateFunction = true;
5099 }
Mike Stump11289f42009-09-09 15:08:12 +00005100 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005101 }
5102
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005103 // If there were 0 or 1 matches, we're done.
5104 if (Matches.empty())
5105 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005106 else if (Matches.size() == 1) {
John McCall58cc69d2010-01-27 01:50:18 +00005107 FunctionDecl *Result = cast<FunctionDecl>(*Matches.begin());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005108 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005109 if (Complain)
5110 CheckUnresolvedAccess(*this, OvlExpr, Result, Matches.begin().getAccess());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005111 return Result;
5112 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005113
5114 // C++ [over.over]p4:
5115 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005116 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005117 // [...] and any given function template specialization F1 is
5118 // eliminated if the set contains a second function template
5119 // specialization whose function template is more specialized
5120 // than the function template of F1 according to the partial
5121 // ordering rules of 14.5.5.2.
5122
5123 // The algorithm specified above is quadratic. We instead use a
5124 // two-pass algorithm (similar to the one used to identify the
5125 // best viable function in an overload set) that identifies the
5126 // best function template (if it exists).
John McCall58cc69d2010-01-27 01:50:18 +00005127
5128 UnresolvedSetIterator Result =
5129 getMostSpecialized(Matches.begin(), Matches.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005130 TPOC_Other, From->getLocStart(),
5131 PDiag(),
5132 PDiag(diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005133 << Matches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005134 PDiag(diag::note_ovl_candidate)
5135 << (unsigned) oc_function_template);
John McCall58cc69d2010-01-27 01:50:18 +00005136 assert(Result != Matches.end() && "no most-specialized template");
5137 MarkDeclarationReferenced(From->getLocStart(), *Result);
5138 if (Complain)
5139 CheckUnresolvedAccess(*this, OvlExpr, *Result, Result.getAccess());
5140 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005141 }
Mike Stump11289f42009-09-09 15:08:12 +00005142
Douglas Gregorfae1d712009-09-26 03:56:17 +00005143 // [...] any function template specializations in the set are
5144 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005145 for (unsigned I = 0, N = Matches.size(); I != N; ) {
5146 if (cast<FunctionDecl>(Matches[I].getDecl())->getPrimaryTemplate() == 0)
5147 ++I;
5148 else {
5149 Matches.erase(I);
5150 --N;
5151 }
5152 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005153
Mike Stump11289f42009-09-09 15:08:12 +00005154 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005155 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005156 if (Matches.size() == 1) {
5157 UnresolvedSetIterator Match = Matches.begin();
5158 MarkDeclarationReferenced(From->getLocStart(), *Match);
5159 if (Complain)
5160 CheckUnresolvedAccess(*this, OvlExpr, *Match, Match.getAccess());
5161 return cast<FunctionDecl>(*Match);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005162 }
Mike Stump11289f42009-09-09 15:08:12 +00005163
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005164 // FIXME: We should probably return the same thing that BestViableFunction
5165 // returns (even if we issue the diagnostics here).
5166 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005167 << Matches[0]->getDeclName();
5168 for (UnresolvedSetIterator I = Matches.begin(),
5169 E = Matches.end(); I != E; ++I)
5170 NoteOverloadCandidate(cast<FunctionDecl>(*I));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005171 return 0;
5172}
5173
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005174/// \brief Given an expression that refers to an overloaded function, try to
5175/// resolve that overloaded function expression down to a single function.
5176///
5177/// This routine can only resolve template-ids that refer to a single function
5178/// template, where that template-id refers to a single template whose template
5179/// arguments are either provided by the template-id or have defaults,
5180/// as described in C++0x [temp.arg.explicit]p3.
5181FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5182 // C++ [over.over]p1:
5183 // [...] [Note: any redundant set of parentheses surrounding the
5184 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005185 // C++ [over.over]p1:
5186 // [...] The overloaded function name can be preceded by the &
5187 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005188
5189 if (From->getType() != Context.OverloadTy)
5190 return 0;
5191
5192 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005193
5194 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005195 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005196 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005197
5198 TemplateArgumentListInfo ExplicitTemplateArgs;
5199 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005200
5201 // Look through all of the overloaded functions, searching for one
5202 // whose type matches exactly.
5203 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005204 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5205 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005206 // C++0x [temp.arg.explicit]p3:
5207 // [...] In contexts where deduction is done and fails, or in contexts
5208 // where deduction is not done, if a template argument list is
5209 // specified and it, along with any default template arguments,
5210 // identifies a single function template specialization, then the
5211 // template-id is an lvalue for the function template specialization.
5212 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5213
5214 // C++ [over.over]p2:
5215 // If the name is a function template, template argument deduction is
5216 // done (14.8.2.2), and if the argument deduction succeeds, the
5217 // resulting template argument list is used to generate a single
5218 // function template specialization, which is added to the set of
5219 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005220 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005221 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005222 if (TemplateDeductionResult Result
5223 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5224 Specialization, Info)) {
5225 // FIXME: make a note of the failed deduction for diagnostics.
5226 (void)Result;
5227 continue;
5228 }
5229
5230 // Multiple matches; we can't resolve to a single declaration.
5231 if (Matched)
5232 return 0;
5233
5234 Matched = Specialization;
5235 }
5236
5237 return Matched;
5238}
5239
Douglas Gregorcabea402009-09-22 15:41:20 +00005240/// \brief Add a single candidate to the overload set.
5241static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00005242 NamedDecl *Callee,
John McCallb89836b2010-01-26 01:37:31 +00005243 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00005244 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005245 Expr **Args, unsigned NumArgs,
5246 OverloadCandidateSet &CandidateSet,
5247 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005248 if (isa<UsingShadowDecl>(Callee))
5249 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5250
Douglas Gregorcabea402009-09-22 15:41:20 +00005251 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005252 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCallb89836b2010-01-26 01:37:31 +00005253 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5254 false, false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005255 return;
John McCalld14a8642009-11-21 08:51:07 +00005256 }
5257
5258 if (FunctionTemplateDecl *FuncTemplate
5259 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCallb89836b2010-01-26 01:37:31 +00005260 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005261 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005262 return;
5263 }
5264
5265 assert(false && "unhandled case in overloaded call candidate");
5266
5267 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005268}
5269
5270/// \brief Add the overload candidates named by callee and/or found by argument
5271/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005272void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005273 Expr **Args, unsigned NumArgs,
5274 OverloadCandidateSet &CandidateSet,
5275 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005276
5277#ifndef NDEBUG
5278 // Verify that ArgumentDependentLookup is consistent with the rules
5279 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005280 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005281 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5282 // and let Y be the lookup set produced by argument dependent
5283 // lookup (defined as follows). If X contains
5284 //
5285 // -- a declaration of a class member, or
5286 //
5287 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005288 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005289 //
5290 // -- a declaration that is neither a function or a function
5291 // template
5292 //
5293 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005294
John McCall57500772009-12-16 12:17:52 +00005295 if (ULE->requiresADL()) {
5296 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5297 E = ULE->decls_end(); I != E; ++I) {
5298 assert(!(*I)->getDeclContext()->isRecord());
5299 assert(isa<UsingShadowDecl>(*I) ||
5300 !(*I)->getDeclContext()->isFunctionOrMethod());
5301 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005302 }
5303 }
5304#endif
5305
John McCall57500772009-12-16 12:17:52 +00005306 // It would be nice to avoid this copy.
5307 TemplateArgumentListInfo TABuffer;
5308 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5309 if (ULE->hasExplicitTemplateArgs()) {
5310 ULE->copyTemplateArgumentsInto(TABuffer);
5311 ExplicitTemplateArgs = &TABuffer;
5312 }
5313
5314 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5315 E = ULE->decls_end(); I != E; ++I)
John McCallb89836b2010-01-26 01:37:31 +00005316 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005317 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005318 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005319
John McCall57500772009-12-16 12:17:52 +00005320 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005321 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5322 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005323 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005324 CandidateSet,
5325 PartialOverloading);
5326}
John McCalld681c392009-12-16 08:11:27 +00005327
John McCall57500772009-12-16 12:17:52 +00005328static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5329 Expr **Args, unsigned NumArgs) {
5330 Fn->Destroy(SemaRef.Context);
5331 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5332 Args[Arg]->Destroy(SemaRef.Context);
5333 return SemaRef.ExprError();
5334}
5335
John McCalld681c392009-12-16 08:11:27 +00005336/// Attempts to recover from a call where no functions were found.
5337///
5338/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005339static Sema::OwningExprResult
5340BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5341 UnresolvedLookupExpr *ULE,
5342 SourceLocation LParenLoc,
5343 Expr **Args, unsigned NumArgs,
5344 SourceLocation *CommaLocs,
5345 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005346
5347 CXXScopeSpec SS;
5348 if (ULE->getQualifier()) {
5349 SS.setScopeRep(ULE->getQualifier());
5350 SS.setRange(ULE->getQualifierRange());
5351 }
5352
John McCall57500772009-12-16 12:17:52 +00005353 TemplateArgumentListInfo TABuffer;
5354 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5355 if (ULE->hasExplicitTemplateArgs()) {
5356 ULE->copyTemplateArgumentsInto(TABuffer);
5357 ExplicitTemplateArgs = &TABuffer;
5358 }
5359
John McCalld681c392009-12-16 08:11:27 +00005360 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5361 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005362 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005363 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005364
John McCall57500772009-12-16 12:17:52 +00005365 assert(!R.empty() && "lookup results empty despite recovery");
5366
5367 // Build an implicit member call if appropriate. Just drop the
5368 // casts and such from the call, we don't really care.
5369 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5370 if ((*R.begin())->isCXXClassMember())
5371 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5372 else if (ExplicitTemplateArgs)
5373 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5374 else
5375 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5376
5377 if (NewFn.isInvalid())
5378 return Destroy(SemaRef, Fn, Args, NumArgs);
5379
5380 Fn->Destroy(SemaRef.Context);
5381
5382 // This shouldn't cause an infinite loop because we're giving it
5383 // an expression with non-empty lookup results, which should never
5384 // end up here.
5385 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5386 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5387 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005388}
Douglas Gregorcabea402009-09-22 15:41:20 +00005389
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005390/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005391/// (which eventually refers to the declaration Func) and the call
5392/// arguments Args/NumArgs, attempt to resolve the function call down
5393/// to a specific function. If overload resolution succeeds, returns
5394/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005395/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005396/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005397Sema::OwningExprResult
5398Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5399 SourceLocation LParenLoc,
5400 Expr **Args, unsigned NumArgs,
5401 SourceLocation *CommaLocs,
5402 SourceLocation RParenLoc) {
5403#ifndef NDEBUG
5404 if (ULE->requiresADL()) {
5405 // To do ADL, we must have found an unqualified name.
5406 assert(!ULE->getQualifier() && "qualified name with ADL");
5407
5408 // We don't perform ADL for implicit declarations of builtins.
5409 // Verify that this was correctly set up.
5410 FunctionDecl *F;
5411 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5412 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5413 F->getBuiltinID() && F->isImplicit())
5414 assert(0 && "performing ADL for builtin");
5415
5416 // We don't perform ADL in C.
5417 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5418 }
5419#endif
5420
John McCallbc077cf2010-02-08 23:07:23 +00005421 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005422
John McCall57500772009-12-16 12:17:52 +00005423 // Add the functions denoted by the callee to the set of candidate
5424 // functions, including those from argument-dependent lookup.
5425 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005426
5427 // If we found nothing, try to recover.
5428 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5429 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005430 if (CandidateSet.empty())
5431 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5432 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005433
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005434 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005435 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005436 case OR_Success: {
5437 FunctionDecl *FDecl = Best->Function;
John McCall58cc69d2010-01-27 01:50:18 +00005438 CheckUnresolvedLookupAccess(ULE, FDecl, Best->getAccess());
John McCall57500772009-12-16 12:17:52 +00005439 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5440 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5441 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005442
5443 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005444 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005445 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005446 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005447 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005448 break;
5449
5450 case OR_Ambiguous:
5451 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005452 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005453 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005454 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005455
5456 case OR_Deleted:
5457 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5458 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005459 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005460 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005461 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005462 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005463 }
5464
5465 // Overload resolution failed. Destroy all of the subexpressions and
5466 // return NULL.
5467 Fn->Destroy(Context);
5468 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5469 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005470 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005471}
5472
John McCall4c4c1df2010-01-26 03:27:55 +00005473static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005474 return Functions.size() > 1 ||
5475 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5476}
5477
Douglas Gregor084d8552009-03-13 23:49:33 +00005478/// \brief Create a unary operation that may resolve to an overloaded
5479/// operator.
5480///
5481/// \param OpLoc The location of the operator itself (e.g., '*').
5482///
5483/// \param OpcIn The UnaryOperator::Opcode that describes this
5484/// operator.
5485///
5486/// \param Functions The set of non-member functions that will be
5487/// considered by overload resolution. The caller needs to build this
5488/// set based on the context using, e.g.,
5489/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5490/// set should not contain any member functions; those will be added
5491/// by CreateOverloadedUnaryOp().
5492///
5493/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005494Sema::OwningExprResult
5495Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5496 const UnresolvedSetImpl &Fns,
5497 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005498 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5499 Expr *Input = (Expr *)input.get();
5500
5501 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5502 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5503 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5504
5505 Expr *Args[2] = { Input, 0 };
5506 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005507
Douglas Gregor084d8552009-03-13 23:49:33 +00005508 // For post-increment and post-decrement, add the implicit '0' as
5509 // the second argument, so that we know this is a post-increment or
5510 // post-decrement.
5511 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5512 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005513 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005514 SourceLocation());
5515 NumArgs = 2;
5516 }
5517
5518 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005519 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005520 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005521 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005522 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005523 /*ADL*/ true, IsOverloaded(Fns));
5524 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005525
Douglas Gregor084d8552009-03-13 23:49:33 +00005526 input.release();
5527 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5528 &Args[0], NumArgs,
5529 Context.DependentTy,
5530 OpLoc));
5531 }
5532
5533 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005534 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005535
5536 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005537 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005538
5539 // Add operator candidates that are member functions.
5540 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5541
John McCall4c4c1df2010-01-26 03:27:55 +00005542 // Add candidates from ADL.
5543 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005544 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005545 /*ExplicitTemplateArgs*/ 0,
5546 CandidateSet);
5547
Douglas Gregor084d8552009-03-13 23:49:33 +00005548 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005549 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005550
5551 // Perform overload resolution.
5552 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005553 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005554 case OR_Success: {
5555 // We found a built-in operator or an overloaded operator.
5556 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005557
Douglas Gregor084d8552009-03-13 23:49:33 +00005558 if (FnDecl) {
5559 // We matched an overloaded operator. Build a call to that
5560 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005561
Douglas Gregor084d8552009-03-13 23:49:33 +00005562 // Convert the arguments.
5563 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005564 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5565
Douglas Gregor084d8552009-03-13 23:49:33 +00005566 if (PerformObjectArgumentInitialization(Input, Method))
5567 return ExprError();
5568 } else {
5569 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005570 OwningExprResult InputInit
5571 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005572 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005573 SourceLocation(),
5574 move(input));
5575 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005576 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005577
Douglas Gregore6600372009-12-23 17:40:29 +00005578 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005579 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005580 }
5581
5582 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005583 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005584
Douglas Gregor084d8552009-03-13 23:49:33 +00005585 // Build the actual expression node.
5586 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5587 SourceLocation());
5588 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005589
Douglas Gregor084d8552009-03-13 23:49:33 +00005590 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005591 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005592 ExprOwningPtr<CallExpr> TheCall(this,
5593 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005594 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005595
5596 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5597 FnDecl))
5598 return ExprError();
5599
5600 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005601 } else {
5602 // We matched a built-in operator. Convert the arguments, then
5603 // break out so that we will build the appropriate built-in
5604 // operator node.
5605 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005606 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005607 return ExprError();
5608
5609 break;
5610 }
5611 }
5612
5613 case OR_No_Viable_Function:
5614 // No viable function; fall through to handling this as a
5615 // built-in operator, which will produce an error message for us.
5616 break;
5617
5618 case OR_Ambiguous:
5619 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5620 << UnaryOperator::getOpcodeStr(Opc)
5621 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005622 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005623 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005624 return ExprError();
5625
5626 case OR_Deleted:
5627 Diag(OpLoc, diag::err_ovl_deleted_oper)
5628 << Best->Function->isDeleted()
5629 << UnaryOperator::getOpcodeStr(Opc)
5630 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005631 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005632 return ExprError();
5633 }
5634
5635 // Either we found no viable overloaded operator or we matched a
5636 // built-in operator. In either case, fall through to trying to
5637 // build a built-in operation.
5638 input.release();
5639 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5640}
5641
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005642/// \brief Create a binary operation that may resolve to an overloaded
5643/// operator.
5644///
5645/// \param OpLoc The location of the operator itself (e.g., '+').
5646///
5647/// \param OpcIn The BinaryOperator::Opcode that describes this
5648/// operator.
5649///
5650/// \param Functions The set of non-member functions that will be
5651/// considered by overload resolution. The caller needs to build this
5652/// set based on the context using, e.g.,
5653/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5654/// set should not contain any member functions; those will be added
5655/// by CreateOverloadedBinOp().
5656///
5657/// \param LHS Left-hand argument.
5658/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005659Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005660Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005661 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005662 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005663 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005664 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005665 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005666
5667 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5668 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5669 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5670
5671 // If either side is type-dependent, create an appropriate dependent
5672 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005673 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00005674 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005675 // If there are no functions to store, just build a dependent
5676 // BinaryOperator or CompoundAssignment.
5677 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5678 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5679 Context.DependentTy, OpLoc));
5680
5681 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5682 Context.DependentTy,
5683 Context.DependentTy,
5684 Context.DependentTy,
5685 OpLoc));
5686 }
John McCall4c4c1df2010-01-26 03:27:55 +00005687
5688 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00005689 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005690 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005691 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005692 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005693 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00005694
John McCall4c4c1df2010-01-26 03:27:55 +00005695 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005696 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005697 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005698 Context.DependentTy,
5699 OpLoc));
5700 }
5701
5702 // If this is the .* operator, which is not overloadable, just
5703 // create a built-in binary operator.
5704 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005705 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005706
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005707 // If this is the assignment operator, we only perform overload resolution
5708 // if the left-hand side is a class or enumeration type. This is actually
5709 // a hack. The standard requires that we do overload resolution between the
5710 // various built-in candidates, but as DR507 points out, this can lead to
5711 // problems. So we do it this way, which pretty much follows what GCC does.
5712 // Note that we go the traditional code path for compound assignment forms.
5713 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005714 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005715
Douglas Gregor084d8552009-03-13 23:49:33 +00005716 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005717 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005718
5719 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005720 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005721
5722 // Add operator candidates that are member functions.
5723 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5724
John McCall4c4c1df2010-01-26 03:27:55 +00005725 // Add candidates from ADL.
5726 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5727 Args, 2,
5728 /*ExplicitTemplateArgs*/ 0,
5729 CandidateSet);
5730
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005731 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005732 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005733
5734 // Perform overload resolution.
5735 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005736 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005737 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005738 // We found a built-in operator or an overloaded operator.
5739 FunctionDecl *FnDecl = Best->Function;
5740
5741 if (FnDecl) {
5742 // We matched an overloaded operator. Build a call to that
5743 // operator.
5744
5745 // Convert the arguments.
5746 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005747 // Best->Access is only meaningful for class members.
5748 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5749
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005750 OwningExprResult Arg1
5751 = PerformCopyInitialization(
5752 InitializedEntity::InitializeParameter(
5753 FnDecl->getParamDecl(0)),
5754 SourceLocation(),
5755 Owned(Args[1]));
5756 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005757 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005758
5759 if (PerformObjectArgumentInitialization(Args[0], Method))
5760 return ExprError();
5761
5762 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005763 } else {
5764 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005765 OwningExprResult Arg0
5766 = PerformCopyInitialization(
5767 InitializedEntity::InitializeParameter(
5768 FnDecl->getParamDecl(0)),
5769 SourceLocation(),
5770 Owned(Args[0]));
5771 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005772 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005773
5774 OwningExprResult Arg1
5775 = PerformCopyInitialization(
5776 InitializedEntity::InitializeParameter(
5777 FnDecl->getParamDecl(1)),
5778 SourceLocation(),
5779 Owned(Args[1]));
5780 if (Arg1.isInvalid())
5781 return ExprError();
5782 Args[0] = LHS = Arg0.takeAs<Expr>();
5783 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005784 }
5785
5786 // Determine the result type
5787 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005788 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005789 ResultTy = ResultTy.getNonReferenceType();
5790
5791 // Build the actual expression node.
5792 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005793 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005794 UsualUnaryConversions(FnExpr);
5795
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005796 ExprOwningPtr<CXXOperatorCallExpr>
5797 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5798 Args, 2, ResultTy,
5799 OpLoc));
5800
5801 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5802 FnDecl))
5803 return ExprError();
5804
5805 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005806 } else {
5807 // We matched a built-in operator. Convert the arguments, then
5808 // break out so that we will build the appropriate built-in
5809 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005810 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005811 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005812 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005813 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005814 return ExprError();
5815
5816 break;
5817 }
5818 }
5819
Douglas Gregor66950a32009-09-30 21:46:01 +00005820 case OR_No_Viable_Function: {
5821 // C++ [over.match.oper]p9:
5822 // If the operator is the operator , [...] and there are no
5823 // viable functions, then the operator is assumed to be the
5824 // built-in operator and interpreted according to clause 5.
5825 if (Opc == BinaryOperator::Comma)
5826 break;
5827
Sebastian Redl027de2a2009-05-21 11:50:50 +00005828 // For class as left operand for assignment or compound assigment operator
5829 // do not fall through to handling in built-in, but report that no overloaded
5830 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005831 OwningExprResult Result = ExprError();
5832 if (Args[0]->getType()->isRecordType() &&
5833 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005834 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5835 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005836 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005837 } else {
5838 // No viable function; try to create a built-in operation, which will
5839 // produce an error. Then, show the non-viable candidates.
5840 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005841 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005842 assert(Result.isInvalid() &&
5843 "C++ binary operator overloading is missing candidates!");
5844 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005845 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005846 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005847 return move(Result);
5848 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005849
5850 case OR_Ambiguous:
5851 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5852 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005853 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005854 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005855 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005856 return ExprError();
5857
5858 case OR_Deleted:
5859 Diag(OpLoc, diag::err_ovl_deleted_oper)
5860 << Best->Function->isDeleted()
5861 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005862 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005863 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005864 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005865 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005866
Douglas Gregor66950a32009-09-30 21:46:01 +00005867 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005868 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005869}
5870
Sebastian Redladba46e2009-10-29 20:17:01 +00005871Action::OwningExprResult
5872Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5873 SourceLocation RLoc,
5874 ExprArg Base, ExprArg Idx) {
5875 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5876 static_cast<Expr*>(Idx.get()) };
5877 DeclarationName OpName =
5878 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5879
5880 // If either side is type-dependent, create an appropriate dependent
5881 // expression.
5882 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5883
John McCall58cc69d2010-01-27 01:50:18 +00005884 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005885 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005886 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005887 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005888 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005889 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005890
5891 Base.release();
5892 Idx.release();
5893 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5894 Args, 2,
5895 Context.DependentTy,
5896 RLoc));
5897 }
5898
5899 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005900 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005901
5902 // Subscript can only be overloaded as a member function.
5903
5904 // Add operator candidates that are member functions.
5905 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5906
5907 // Add builtin operator candidates.
5908 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5909
5910 // Perform overload resolution.
5911 OverloadCandidateSet::iterator Best;
5912 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5913 case OR_Success: {
5914 // We found a built-in operator or an overloaded operator.
5915 FunctionDecl *FnDecl = Best->Function;
5916
5917 if (FnDecl) {
5918 // We matched an overloaded operator. Build a call to that
5919 // operator.
5920
John McCallb3a44002010-01-28 01:42:12 +00005921 CheckMemberOperatorAccess(LLoc, Args[0], FnDecl, Best->getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005922
Sebastian Redladba46e2009-10-29 20:17:01 +00005923 // Convert the arguments.
5924 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Anders Carlssona68e51e2010-01-29 18:37:50 +00005925 if (PerformObjectArgumentInitialization(Args[0], Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00005926 return ExprError();
5927
Anders Carlssona68e51e2010-01-29 18:37:50 +00005928 // Convert the arguments.
5929 OwningExprResult InputInit
5930 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5931 FnDecl->getParamDecl(0)),
5932 SourceLocation(),
5933 Owned(Args[1]));
5934 if (InputInit.isInvalid())
5935 return ExprError();
5936
5937 Args[1] = InputInit.takeAs<Expr>();
5938
Sebastian Redladba46e2009-10-29 20:17:01 +00005939 // Determine the result type
5940 QualType ResultTy
5941 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5942 ResultTy = ResultTy.getNonReferenceType();
5943
5944 // Build the actual expression node.
5945 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5946 LLoc);
5947 UsualUnaryConversions(FnExpr);
5948
5949 Base.release();
5950 Idx.release();
5951 ExprOwningPtr<CXXOperatorCallExpr>
5952 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5953 FnExpr, Args, 2,
5954 ResultTy, RLoc));
5955
5956 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5957 FnDecl))
5958 return ExprError();
5959
5960 return MaybeBindToTemporary(TheCall.release());
5961 } else {
5962 // We matched a built-in operator. Convert the arguments, then
5963 // break out so that we will build the appropriate built-in
5964 // operator node.
5965 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005966 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005967 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005968 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005969 return ExprError();
5970
5971 break;
5972 }
5973 }
5974
5975 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005976 if (CandidateSet.empty())
5977 Diag(LLoc, diag::err_ovl_no_oper)
5978 << Args[0]->getType() << /*subscript*/ 0
5979 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5980 else
5981 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5982 << Args[0]->getType()
5983 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005984 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005985 "[]", LLoc);
5986 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005987 }
5988
5989 case OR_Ambiguous:
5990 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5991 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005992 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005993 "[]", LLoc);
5994 return ExprError();
5995
5996 case OR_Deleted:
5997 Diag(LLoc, diag::err_ovl_deleted_oper)
5998 << Best->Function->isDeleted() << "[]"
5999 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006000 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006001 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006002 return ExprError();
6003 }
6004
6005 // We matched a built-in operator; build it.
6006 Base.release();
6007 Idx.release();
6008 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6009 Owned(Args[1]), RLoc);
6010}
6011
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006012/// BuildCallToMemberFunction - Build a call to a member
6013/// function. MemExpr is the expression that refers to the member
6014/// function (and includes the object parameter), Args/NumArgs are the
6015/// arguments to the function call (not including the object
6016/// parameter). The caller needs to validate that the member
6017/// expression refers to a member function or an overloaded member
6018/// function.
John McCall2d74de92009-12-01 22:10:20 +00006019Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006020Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6021 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006022 unsigned NumArgs, SourceLocation *CommaLocs,
6023 SourceLocation RParenLoc) {
6024 // Dig out the member expression. This holds both the object
6025 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006026 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6027
John McCall10eae182009-11-30 22:42:35 +00006028 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006029 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00006030 if (isa<MemberExpr>(NakedMemExpr)) {
6031 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006032 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
6033 } else {
6034 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00006035
John McCall6e9f8f62009-12-03 04:06:58 +00006036 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006037
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006038 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006039 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006040
John McCall2d74de92009-12-01 22:10:20 +00006041 // FIXME: avoid copy.
6042 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6043 if (UnresExpr->hasExplicitTemplateArgs()) {
6044 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6045 TemplateArgs = &TemplateArgsBuffer;
6046 }
6047
John McCall10eae182009-11-30 22:42:35 +00006048 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6049 E = UnresExpr->decls_end(); I != E; ++I) {
6050
John McCall6e9f8f62009-12-03 04:06:58 +00006051 NamedDecl *Func = *I;
6052 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6053 if (isa<UsingShadowDecl>(Func))
6054 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6055
John McCall10eae182009-11-30 22:42:35 +00006056 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006057 // If explicit template arguments were provided, we can't call a
6058 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006059 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006060 continue;
6061
John McCallb89836b2010-01-26 01:37:31 +00006062 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
6063 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006064 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006065 } else {
John McCall10eae182009-11-30 22:42:35 +00006066 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCallb89836b2010-01-26 01:37:31 +00006067 I.getAccess(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006068 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006069 CandidateSet,
6070 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006071 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006072 }
Mike Stump11289f42009-09-09 15:08:12 +00006073
John McCall10eae182009-11-30 22:42:35 +00006074 DeclarationName DeclName = UnresExpr->getMemberName();
6075
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006076 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006077 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006078 case OR_Success:
6079 Method = cast<CXXMethodDecl>(Best->Function);
John McCall58cc69d2010-01-27 01:50:18 +00006080 CheckUnresolvedMemberAccess(UnresExpr, Method, Best->getAccess());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006081 break;
6082
6083 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006084 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006085 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006086 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006087 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006088 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006089 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006090
6091 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006092 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006093 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006094 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006095 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006096 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006097
6098 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006099 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006100 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006101 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006102 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006103 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006104 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006105 }
6106
Douglas Gregor51c538b2009-11-20 19:42:02 +00006107 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00006108
John McCall2d74de92009-12-01 22:10:20 +00006109 // If overload resolution picked a static member, build a
6110 // non-member call based on that function.
6111 if (Method->isStatic()) {
6112 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6113 Args, NumArgs, RParenLoc);
6114 }
6115
John McCall10eae182009-11-30 22:42:35 +00006116 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006117 }
6118
6119 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006120 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006121 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006122 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006123 Method->getResultType().getNonReferenceType(),
6124 RParenLoc));
6125
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006126 // Check for a valid return type.
6127 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6128 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006129 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006130
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006131 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00006132 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006133 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006134 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00006135 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006136 MemExpr->setBase(ObjectArg);
6137
6138 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006139 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006140 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006141 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006142 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006143
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006144 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006145 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006146
John McCall2d74de92009-12-01 22:10:20 +00006147 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006148}
6149
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006150/// BuildCallToObjectOfClassType - Build a call to an object of class
6151/// type (C++ [over.call.object]), which can end up invoking an
6152/// overloaded function call operator (@c operator()) or performing a
6153/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006154Sema::ExprResult
6155Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006156 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006157 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006158 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006159 SourceLocation RParenLoc) {
6160 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006161 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006162
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006163 // C++ [over.call.object]p1:
6164 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006165 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006166 // candidate functions includes at least the function call
6167 // operators of T. The function call operators of T are obtained by
6168 // ordinary lookup of the name operator() in the context of
6169 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006170 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006171 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006172
6173 if (RequireCompleteType(LParenLoc, Object->getType(),
6174 PartialDiagnostic(diag::err_incomplete_object_call)
6175 << Object->getSourceRange()))
6176 return true;
6177
John McCall27b18f82009-11-17 02:14:36 +00006178 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6179 LookupQualifiedName(R, Record->getDecl());
6180 R.suppressDiagnostics();
6181
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006182 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006183 Oper != OperEnd; ++Oper) {
John McCallb89836b2010-01-26 01:37:31 +00006184 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6185 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006186 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006187 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006188
Douglas Gregorab7897a2008-11-19 22:57:39 +00006189 // C++ [over.call.object]p2:
6190 // In addition, for each conversion function declared in T of the
6191 // form
6192 //
6193 // operator conversion-type-id () cv-qualifier;
6194 //
6195 // where cv-qualifier is the same cv-qualification as, or a
6196 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006197 // denotes the type "pointer to function of (P1,...,Pn) returning
6198 // R", or the type "reference to pointer to function of
6199 // (P1,...,Pn) returning R", or the type "reference to function
6200 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006201 // is also considered as a candidate function. Similarly,
6202 // surrogate call functions are added to the set of candidate
6203 // functions for each conversion function declared in an
6204 // accessible base class provided the function is not hidden
6205 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006206 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006207 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006208 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006209 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006210 NamedDecl *D = *I;
6211 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6212 if (isa<UsingShadowDecl>(D))
6213 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6214
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006215 // Skip over templated conversion functions; they aren't
6216 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006217 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006218 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006219
John McCall6e9f8f62009-12-03 04:06:58 +00006220 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006221
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006222 // Strip the reference type (if any) and then the pointer type (if
6223 // any) to get down to what might be a function type.
6224 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6225 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6226 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006227
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006228 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCallb89836b2010-01-26 01:37:31 +00006229 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006230 Object->getType(), Args, NumArgs,
6231 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006232 }
Mike Stump11289f42009-09-09 15:08:12 +00006233
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006234 // Perform overload resolution.
6235 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006236 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006237 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006238 // Overload resolution succeeded; we'll build the appropriate call
6239 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006240 break;
6241
6242 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006243 if (CandidateSet.empty())
6244 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6245 << Object->getType() << /*call*/ 1
6246 << Object->getSourceRange();
6247 else
6248 Diag(Object->getSourceRange().getBegin(),
6249 diag::err_ovl_no_viable_object_call)
6250 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006251 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006252 break;
6253
6254 case OR_Ambiguous:
6255 Diag(Object->getSourceRange().getBegin(),
6256 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006257 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006258 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006259 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006260
6261 case OR_Deleted:
6262 Diag(Object->getSourceRange().getBegin(),
6263 diag::err_ovl_deleted_object_call)
6264 << Best->Function->isDeleted()
6265 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006266 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006267 break;
Mike Stump11289f42009-09-09 15:08:12 +00006268 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006269
Douglas Gregorab7897a2008-11-19 22:57:39 +00006270 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006271 // We had an error; delete all of the subexpressions and return
6272 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006273 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006274 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006275 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006276 return true;
6277 }
6278
Douglas Gregorab7897a2008-11-19 22:57:39 +00006279 if (Best->Function == 0) {
6280 // Since there is no function declaration, this is one of the
6281 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006282 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006283 = cast<CXXConversionDecl>(
6284 Best->Conversions[0].UserDefined.ConversionFunction);
6285
John McCall2cb94162010-01-28 07:38:46 +00006286 CheckMemberOperatorAccess(LParenLoc, Object, Conv, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006287
Douglas Gregorab7897a2008-11-19 22:57:39 +00006288 // We selected one of the surrogate functions that converts the
6289 // object parameter to a function pointer. Perform the conversion
6290 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006291
6292 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006293 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006294 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006295
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006296 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006297 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6298 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006299 }
6300
John McCall2cb94162010-01-28 07:38:46 +00006301 CheckMemberOperatorAccess(LParenLoc, Object,
6302 Best->Function, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006303
Douglas Gregorab7897a2008-11-19 22:57:39 +00006304 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6305 // that calls this method, using Object for the implicit object
6306 // parameter and passing along the remaining arguments.
6307 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006308 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006309
6310 unsigned NumArgsInProto = Proto->getNumArgs();
6311 unsigned NumArgsToCheck = NumArgs;
6312
6313 // Build the full argument list for the method call (the
6314 // implicit object parameter is placed at the beginning of the
6315 // list).
6316 Expr **MethodArgs;
6317 if (NumArgs < NumArgsInProto) {
6318 NumArgsToCheck = NumArgsInProto;
6319 MethodArgs = new Expr*[NumArgsInProto + 1];
6320 } else {
6321 MethodArgs = new Expr*[NumArgs + 1];
6322 }
6323 MethodArgs[0] = Object;
6324 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6325 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006326
6327 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006328 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006329 UsualUnaryConversions(NewFn);
6330
6331 // Once we've built TheCall, all of the expressions are properly
6332 // owned.
6333 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006334 ExprOwningPtr<CXXOperatorCallExpr>
6335 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006336 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006337 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006338 delete [] MethodArgs;
6339
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006340 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6341 Method))
6342 return true;
6343
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006344 // We may have default arguments. If so, we need to allocate more
6345 // slots in the call for them.
6346 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006347 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006348 else if (NumArgs > NumArgsInProto)
6349 NumArgsToCheck = NumArgsInProto;
6350
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006351 bool IsError = false;
6352
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006353 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006354 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006355 TheCall->setArg(0, Object);
6356
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006357
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006358 // Check the argument types.
6359 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006360 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006361 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006362 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006363
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006364 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006365
6366 OwningExprResult InputInit
6367 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6368 Method->getParamDecl(i)),
6369 SourceLocation(), Owned(Arg));
6370
6371 IsError |= InputInit.isInvalid();
6372 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006373 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006374 OwningExprResult DefArg
6375 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6376 if (DefArg.isInvalid()) {
6377 IsError = true;
6378 break;
6379 }
6380
6381 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006382 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006383
6384 TheCall->setArg(i + 1, Arg);
6385 }
6386
6387 // If this is a variadic call, handle args passed through "...".
6388 if (Proto->isVariadic()) {
6389 // Promote the arguments (C99 6.5.2.2p7).
6390 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6391 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006392 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006393 TheCall->setArg(i + 1, Arg);
6394 }
6395 }
6396
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006397 if (IsError) return true;
6398
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006399 if (CheckFunctionCall(Method, TheCall.get()))
6400 return true;
6401
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006402 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006403}
6404
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006405/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006406/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006407/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006408Sema::OwningExprResult
6409Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6410 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006411 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006412
John McCallbc077cf2010-02-08 23:07:23 +00006413 SourceLocation Loc = Base->getExprLoc();
6414
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006415 // C++ [over.ref]p1:
6416 //
6417 // [...] An expression x->m is interpreted as (x.operator->())->m
6418 // for a class object x of type T if T::operator->() exists and if
6419 // the operator is selected as the best match function by the
6420 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006421 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006422 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006423 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006424
John McCallbc077cf2010-02-08 23:07:23 +00006425 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006426 PDiag(diag::err_typecheck_incomplete_tag)
6427 << Base->getSourceRange()))
6428 return ExprError();
6429
John McCall27b18f82009-11-17 02:14:36 +00006430 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6431 LookupQualifiedName(R, BaseRecord->getDecl());
6432 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006433
6434 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006435 Oper != OperEnd; ++Oper) {
6436 NamedDecl *D = *Oper;
6437 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6438 if (isa<UsingShadowDecl>(D))
6439 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6440
John McCallb89836b2010-01-26 01:37:31 +00006441 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00006442 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006443 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006444 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006445
6446 // Perform overload resolution.
6447 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006448 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006449 case OR_Success:
6450 // Overload resolution succeeded; we'll build the call below.
6451 break;
6452
6453 case OR_No_Viable_Function:
6454 if (CandidateSet.empty())
6455 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006456 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006457 else
6458 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006459 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006460 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006461 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006462
6463 case OR_Ambiguous:
6464 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006465 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006466 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006467 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006468
6469 case OR_Deleted:
6470 Diag(OpLoc, diag::err_ovl_deleted_oper)
6471 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006472 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006473 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006474 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006475 }
6476
6477 // Convert the object parameter.
6478 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006479 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006480 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006481
6482 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006483 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006484
6485 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006486 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6487 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006488 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006489
6490 QualType ResultTy = Method->getResultType().getNonReferenceType();
6491 ExprOwningPtr<CXXOperatorCallExpr>
6492 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6493 &Base, 1, ResultTy, OpLoc));
6494
6495 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6496 Method))
6497 return ExprError();
6498 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006499}
6500
Douglas Gregorcd695e52008-11-10 20:40:00 +00006501/// FixOverloadedFunctionReference - E is an expression that refers to
6502/// a C++ overloaded function (possibly with some parentheses and
6503/// perhaps a '&' around it). We have resolved the overloaded function
6504/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006505/// refer (possibly indirectly) to Fn. Returns the new expr.
6506Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006507 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006508 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6509 if (SubExpr == PE->getSubExpr())
6510 return PE->Retain();
6511
6512 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6513 }
6514
6515 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6516 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006517 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006518 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006519 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006520 if (SubExpr == ICE->getSubExpr())
6521 return ICE->Retain();
6522
6523 return new (Context) ImplicitCastExpr(ICE->getType(),
6524 ICE->getCastKind(),
6525 SubExpr,
6526 ICE->isLvalueCast());
6527 }
6528
6529 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006530 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006531 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006532 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6533 if (Method->isStatic()) {
6534 // Do nothing: static member functions aren't any different
6535 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006536 } else {
John McCalle66edc12009-11-24 19:00:30 +00006537 // Fix the sub expression, which really has to be an
6538 // UnresolvedLookupExpr holding an overloaded member function
6539 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006540 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6541 if (SubExpr == UnOp->getSubExpr())
6542 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006543
John McCalld14a8642009-11-21 08:51:07 +00006544 assert(isa<DeclRefExpr>(SubExpr)
6545 && "fixed to something other than a decl ref");
6546 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6547 && "fixed to a member ref with no nested name qualifier");
6548
6549 // We have taken the address of a pointer to member
6550 // function. Perform the computation here so that we get the
6551 // appropriate pointer to member type.
6552 QualType ClassType
6553 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6554 QualType MemPtrType
6555 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6556
6557 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6558 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006559 }
6560 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006561 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6562 if (SubExpr == UnOp->getSubExpr())
6563 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006564
Douglas Gregor51c538b2009-11-20 19:42:02 +00006565 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6566 Context.getPointerType(SubExpr->getType()),
6567 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006568 }
John McCalld14a8642009-11-21 08:51:07 +00006569
6570 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006571 // FIXME: avoid copy.
6572 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006573 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006574 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6575 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006576 }
6577
John McCalld14a8642009-11-21 08:51:07 +00006578 return DeclRefExpr::Create(Context,
6579 ULE->getQualifier(),
6580 ULE->getQualifierRange(),
6581 Fn,
6582 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006583 Fn->getType(),
6584 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006585 }
6586
John McCall10eae182009-11-30 22:42:35 +00006587 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006588 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006589 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6590 if (MemExpr->hasExplicitTemplateArgs()) {
6591 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6592 TemplateArgs = &TemplateArgsBuffer;
6593 }
John McCall6b51f282009-11-23 01:53:49 +00006594
John McCall2d74de92009-12-01 22:10:20 +00006595 Expr *Base;
6596
6597 // If we're filling in
6598 if (MemExpr->isImplicitAccess()) {
6599 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6600 return DeclRefExpr::Create(Context,
6601 MemExpr->getQualifier(),
6602 MemExpr->getQualifierRange(),
6603 Fn,
6604 MemExpr->getMemberLoc(),
6605 Fn->getType(),
6606 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006607 } else {
6608 SourceLocation Loc = MemExpr->getMemberLoc();
6609 if (MemExpr->getQualifier())
6610 Loc = MemExpr->getQualifierRange().getBegin();
6611 Base = new (Context) CXXThisExpr(Loc,
6612 MemExpr->getBaseType(),
6613 /*isImplicit=*/true);
6614 }
John McCall2d74de92009-12-01 22:10:20 +00006615 } else
6616 Base = MemExpr->getBase()->Retain();
6617
6618 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006619 MemExpr->isArrow(),
6620 MemExpr->getQualifier(),
6621 MemExpr->getQualifierRange(),
6622 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006623 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006624 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006625 Fn->getType());
6626 }
6627
Douglas Gregor51c538b2009-11-20 19:42:02 +00006628 assert(false && "Invalid reference to overloaded function");
6629 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006630}
6631
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006632Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6633 FunctionDecl *Fn) {
6634 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6635}
6636
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006637} // end namespace clang