blob: b79b1cc9937540558bd43520198c41fcd90b93ac [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,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000083 ICR_Conversion
84 };
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) {
456 ICS.setBad();
457 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
458 return ICS;
459 }
460
461 OverloadCandidateSet Conversions(From->getExprLoc());
462 OverloadingResult UserDefResult
463 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
464 !SuppressUserConversions, AllowExplicit,
465 ForceRValue, UserCast);
466
467 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000468 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000469 // C++ [over.ics.user]p4:
470 // A conversion of an expression of class type to the same class
471 // type is given Exact Match rank, and a conversion of an
472 // expression of class type to a base class of that type is
473 // given Conversion rank, in spite of the fact that a copy
474 // constructor (i.e., a user-defined conversion function) is
475 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000476 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000477 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000478 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000479 = Context.getCanonicalType(From->getType().getUnqualifiedType());
480 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000481 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000482 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000483 // Turn this into a "standard" conversion sequence, so that it
484 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000485 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000486 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000487 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000488 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000489 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000490 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000491 ICS.Standard.Second = ICK_Derived_To_Base;
492 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000493 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000494
495 // C++ [over.best.ics]p4:
496 // However, when considering the argument of a user-defined
497 // conversion function that is a candidate by 13.3.1.3 when
498 // invoked for the copying of the temporary in the second step
499 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
500 // 13.3.1.6 in all cases, only standard conversion sequences and
501 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000502 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall0d1da222010-01-12 00:44:57 +0000503 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000504 ICS.Bad.init(BadConversionSequence::suppressed_user, From, ToType);
505 }
John McCalle8c8cd22010-01-13 22:30:33 +0000506 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000507 ICS.setAmbiguous();
508 ICS.Ambiguous.setFromType(From->getType());
509 ICS.Ambiguous.setToType(ToType);
510 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
511 Cand != Conversions.end(); ++Cand)
512 if (Cand->Viable)
513 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000514 } else {
John McCall0d1da222010-01-12 00:44:57 +0000515 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000516 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000517 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000518
519 return ICS;
520}
521
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000522/// \brief Determine whether the conversion from FromType to ToType is a valid
523/// conversion that strips "noreturn" off the nested function type.
524static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
525 QualType ToType, QualType &ResultTy) {
526 if (Context.hasSameUnqualifiedType(FromType, ToType))
527 return false;
528
529 // Strip the noreturn off the type we're converting from; noreturn can
530 // safely be removed.
531 FromType = Context.getNoReturnType(FromType, false);
532 if (!Context.hasSameUnqualifiedType(FromType, ToType))
533 return false;
534
535 ResultTy = FromType;
536 return true;
537}
538
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000539/// IsStandardConversion - Determines whether there is a standard
540/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
541/// expression From to the type ToType. Standard conversion sequences
542/// only consider non-class types; for conversions that involve class
543/// types, use TryImplicitConversion. If a conversion exists, SCS will
544/// contain the standard conversion sequence required to perform this
545/// conversion and this routine will return true. Otherwise, this
546/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000547bool
548Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000549 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000550 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551 QualType FromType = From->getType();
552
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000553 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000554 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000555 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000556 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000557 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000558 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000559
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000560 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000561 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000562 if (FromType->isRecordType() || ToType->isRecordType()) {
563 if (getLangOptions().CPlusPlus)
564 return false;
565
Mike Stump11289f42009-09-09 15:08:12 +0000566 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000567 }
568
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569 // The first conversion can be an lvalue-to-rvalue conversion,
570 // array-to-pointer conversion, or function-to-pointer conversion
571 // (C++ 4p1).
572
Mike Stump11289f42009-09-09 15:08:12 +0000573 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000574 // An lvalue (3.10) of a non-function, non-array type T can be
575 // converted to an rvalue.
576 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000577 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000578 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000579 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000580 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000581
582 // If T is a non-class type, the type of the rvalue is the
583 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000584 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
585 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000586 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000587 } else if (FromType->isArrayType()) {
588 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000589 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000590
591 // An lvalue or rvalue of type "array of N T" or "array of unknown
592 // bound of T" can be converted to an rvalue of type "pointer to
593 // T" (C++ 4.2p1).
594 FromType = Context.getArrayDecayedType(FromType);
595
596 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
597 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000598 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000599
600 // For the purpose of ranking in overload resolution
601 // (13.3.3.1.1), this conversion is considered an
602 // array-to-pointer conversion followed by a qualification
603 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000604 SCS.Second = ICK_Identity;
605 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000606 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000607 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000608 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
610 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000611 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612
613 // An lvalue of function type T can be converted to an rvalue of
614 // type "pointer to T." The result is a pointer to the
615 // function. (C++ 4.3p1).
616 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000617 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000618 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000619 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000620 SCS.First = ICK_Function_To_Pointer;
621
622 // We were able to resolve the address of the overloaded function,
623 // so we can convert to the type of that function.
624 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000625 if (ToType->isLValueReferenceType())
626 FromType = Context.getLValueReferenceType(FromType);
627 else if (ToType->isRValueReferenceType())
628 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000629 else if (ToType->isMemberPointerType()) {
630 // Resolve address only succeeds if both sides are member pointers,
631 // but it doesn't have to be the same class. See DR 247.
632 // Note that this means that the type of &Derived::fn can be
633 // Ret (Base::*)(Args) if the fn overload actually found is from the
634 // base class, even if it was brought into the derived class via a
635 // using declaration. The standard isn't clear on this issue at all.
636 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
637 FromType = Context.getMemberPointerType(FromType,
638 Context.getTypeDeclType(M->getParent()).getTypePtr());
639 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000640 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000641 } else {
642 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000643 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000644 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000645 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000646
647 // The second conversion can be an integral promotion, floating
648 // point promotion, integral conversion, floating point conversion,
649 // floating-integral conversion, pointer conversion,
650 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000651 // For overloading in C, this can also be a "compatible-type"
652 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000653 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000654 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000655 // The unqualified versions of the types are the same: there's no
656 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000657 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000658 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000659 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000661 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000662 } else if (IsFloatingPointPromotion(FromType, ToType)) {
663 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000664 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000665 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000666 } else if (IsComplexPromotion(FromType, ToType)) {
667 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000668 SCS.Second = ICK_Complex_Promotion;
669 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000670 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000671 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000672 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000673 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000674 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000675 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
676 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000677 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000678 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000679 } else if (FromType->isComplexType() && ToType->isComplexType()) {
680 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000681 SCS.Second = ICK_Complex_Conversion;
682 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000683 } else if ((FromType->isFloatingType() &&
684 ToType->isIntegralType() && (!ToType->isBooleanType() &&
685 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000686 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000687 ToType->isFloatingType())) {
688 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000689 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000690 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000691 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
692 (ToType->isComplexType() && FromType->isArithmeticType())) {
693 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000694 SCS.Second = ICK_Complex_Real;
695 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000696 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
697 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000698 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000699 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000700 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000701 } else if (IsMemberPointerConversion(From, FromType, ToType,
702 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000703 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000704 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000705 } else if (ToType->isBooleanType() &&
706 (FromType->isArithmeticType() ||
707 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000708 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000709 FromType->isBlockPointerType() ||
710 FromType->isMemberPointerType() ||
711 FromType->isNullPtrType())) {
712 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000713 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000715 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000716 Context.typesAreCompatible(ToType, FromType)) {
717 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000718 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000719 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
720 // Treat a conversion that strips "noreturn" as an identity conversion.
721 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 } else {
723 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000724 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000726 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000727
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000728 QualType CanonFrom;
729 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000730 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000731 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000732 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000733 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000734 CanonFrom = Context.getCanonicalType(FromType);
735 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000736 } else {
737 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000738 SCS.Third = ICK_Identity;
739
Mike Stump11289f42009-09-09 15:08:12 +0000740 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000741 // [...] Any difference in top-level cv-qualification is
742 // subsumed by the initialization itself and does not constitute
743 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000744 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000745 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000746 if (CanonFrom.getLocalUnqualifiedType()
747 == CanonTo.getLocalUnqualifiedType() &&
748 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000749 FromType = ToType;
750 CanonFrom = CanonTo;
751 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000753 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754
755 // If we have not converted the argument type to the parameter type,
756 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000757 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000758 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000759
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000760 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000761}
762
763/// IsIntegralPromotion - Determines whether the conversion from the
764/// expression From (whose potentially-adjusted type is FromType) to
765/// ToType is an integral promotion (C++ 4.5). If so, returns true and
766/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000767bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000768 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000769 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000770 if (!To) {
771 return false;
772 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000773
774 // An rvalue of type char, signed char, unsigned char, short int, or
775 // unsigned short int can be converted to an rvalue of type int if
776 // int can represent all the values of the source type; otherwise,
777 // the source rvalue can be converted to an rvalue of type unsigned
778 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000779 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
780 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000781 if (// We can promote any signed, promotable integer type to an int
782 (FromType->isSignedIntegerType() ||
783 // We can promote any unsigned integer type whose size is
784 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000785 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000786 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000788 }
789
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000790 return To->getKind() == BuiltinType::UInt;
791 }
792
793 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
794 // can be converted to an rvalue of the first of the following types
795 // that can represent all the values of its underlying type: int,
796 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000797
798 // We pre-calculate the promotion type for enum types.
799 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
800 if (ToType->isIntegerType())
801 return Context.hasSameUnqualifiedType(ToType,
802 FromEnumType->getDecl()->getPromotionType());
803
804 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000805 // Determine whether the type we're converting from is signed or
806 // unsigned.
807 bool FromIsSigned;
808 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000809
810 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
811 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000812
813 // The types we'll try to promote to, in the appropriate
814 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000815 QualType PromoteTypes[6] = {
816 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000817 Context.LongTy, Context.UnsignedLongTy ,
818 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000819 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000820 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000821 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
822 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000823 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000824 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
825 // We found the type that we can promote to. If this is the
826 // type we wanted, we have a promotion. Otherwise, no
827 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000828 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000829 }
830 }
831 }
832
833 // An rvalue for an integral bit-field (9.6) can be converted to an
834 // rvalue of type int if int can represent all the values of the
835 // bit-field; otherwise, it can be converted to unsigned int if
836 // unsigned int can represent all the values of the bit-field. If
837 // the bit-field is larger yet, no integral promotion applies to
838 // it. If the bit-field has an enumerated type, it is treated as any
839 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000840 // FIXME: We should delay checking of bit-fields until we actually perform the
841 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000842 using llvm::APSInt;
843 if (From)
844 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000845 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000846 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
847 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
848 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
849 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000850
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000851 // Are we promoting to an int from a bitfield that fits in an int?
852 if (BitWidth < ToSize ||
853 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
854 return To->getKind() == BuiltinType::Int;
855 }
Mike Stump11289f42009-09-09 15:08:12 +0000856
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000857 // Are we promoting to an unsigned int from an unsigned bitfield
858 // that fits into an unsigned int?
859 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
860 return To->getKind() == BuiltinType::UInt;
861 }
Mike Stump11289f42009-09-09 15:08:12 +0000862
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000863 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000864 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000865 }
Mike Stump11289f42009-09-09 15:08:12 +0000866
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000867 // An rvalue of type bool can be converted to an rvalue of type int,
868 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000869 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000870 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000871 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872
873 return false;
874}
875
876/// IsFloatingPointPromotion - Determines whether the conversion from
877/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
878/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000879bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880 /// An rvalue of type float can be converted to an rvalue of type
881 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000882 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
883 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000884 if (FromBuiltin->getKind() == BuiltinType::Float &&
885 ToBuiltin->getKind() == BuiltinType::Double)
886 return true;
887
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000888 // C99 6.3.1.5p1:
889 // When a float is promoted to double or long double, or a
890 // double is promoted to long double [...].
891 if (!getLangOptions().CPlusPlus &&
892 (FromBuiltin->getKind() == BuiltinType::Float ||
893 FromBuiltin->getKind() == BuiltinType::Double) &&
894 (ToBuiltin->getKind() == BuiltinType::LongDouble))
895 return true;
896 }
897
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000898 return false;
899}
900
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000901/// \brief Determine if a conversion is a complex promotion.
902///
903/// A complex promotion is defined as a complex -> complex conversion
904/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000905/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000906bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000907 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000908 if (!FromComplex)
909 return false;
910
John McCall9dd450b2009-09-21 23:43:11 +0000911 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000912 if (!ToComplex)
913 return false;
914
915 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000916 ToComplex->getElementType()) ||
917 IsIntegralPromotion(0, FromComplex->getElementType(),
918 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000919}
920
Douglas Gregor237f96c2008-11-26 23:31:11 +0000921/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
922/// the pointer type FromPtr to a pointer to type ToPointee, with the
923/// same type qualifiers as FromPtr has on its pointee type. ToType,
924/// if non-empty, will be a pointer to ToType that may or may not have
925/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000926static QualType
927BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000928 QualType ToPointee, QualType ToType,
929 ASTContext &Context) {
930 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
931 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000932 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000933
934 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000935 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000936 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000937 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000938 return ToType;
939
940 // Build a pointer to ToPointee. It has the right qualifiers
941 // already.
942 return Context.getPointerType(ToPointee);
943 }
944
945 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000946 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000947 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
948 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000949}
950
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000951/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
952/// the FromType, which is an objective-c pointer, to ToType, which may or may
953/// not have the right set of qualifiers.
954static QualType
955BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
956 QualType ToType,
957 ASTContext &Context) {
958 QualType CanonFromType = Context.getCanonicalType(FromType);
959 QualType CanonToType = Context.getCanonicalType(ToType);
960 Qualifiers Quals = CanonFromType.getQualifiers();
961
962 // Exact qualifier match -> return the pointer type we're converting to.
963 if (CanonToType.getLocalQualifiers() == Quals)
964 return ToType;
965
966 // Just build a canonical type that has the right qualifiers.
967 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
968}
969
Mike Stump11289f42009-09-09 15:08:12 +0000970static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000971 bool InOverloadResolution,
972 ASTContext &Context) {
973 // Handle value-dependent integral null pointer constants correctly.
974 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
975 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
976 Expr->getType()->isIntegralType())
977 return !InOverloadResolution;
978
Douglas Gregor56751b52009-09-25 04:25:58 +0000979 return Expr->isNullPointerConstant(Context,
980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
981 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000982}
Mike Stump11289f42009-09-09 15:08:12 +0000983
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000984/// IsPointerConversion - Determines whether the conversion of the
985/// expression From, which has the (possibly adjusted) type FromType,
986/// can be converted to the type ToType via a pointer conversion (C++
987/// 4.10). If so, returns true and places the converted type (that
988/// might differ from ToType in its cv-qualifiers at some level) into
989/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000990///
Douglas Gregora29dc052008-11-27 01:19:21 +0000991/// This routine also supports conversions to and from block pointers
992/// and conversions with Objective-C's 'id', 'id<protocols...>', and
993/// pointers to interfaces. FIXME: Once we've determined the
994/// appropriate overloading rules for Objective-C, we may want to
995/// split the Objective-C checks into a different routine; however,
996/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000997/// conversions, so for now they live here. IncompatibleObjC will be
998/// set if the conversion is an allowed Objective-C conversion that
999/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001000bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001001 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001002 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001003 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001004 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001005 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1006 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001007
Mike Stump11289f42009-09-09 15:08:12 +00001008 // Conversion from a null pointer constant to any Objective-C pointer type.
1009 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001010 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001011 ConvertedType = ToType;
1012 return true;
1013 }
1014
Douglas Gregor231d1c62008-11-27 00:15:41 +00001015 // Blocks: Block pointers can be converted to void*.
1016 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001017 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001018 ConvertedType = ToType;
1019 return true;
1020 }
1021 // Blocks: A null pointer constant can be converted to a block
1022 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001023 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001024 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001025 ConvertedType = ToType;
1026 return true;
1027 }
1028
Sebastian Redl576fd422009-05-10 18:38:11 +00001029 // If the left-hand-side is nullptr_t, the right side can be a null
1030 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001031 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001032 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001033 ConvertedType = ToType;
1034 return true;
1035 }
1036
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001037 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001038 if (!ToTypePtr)
1039 return false;
1040
1041 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001042 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001043 ConvertedType = ToType;
1044 return true;
1045 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001046
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001047 // Beyond this point, both types need to be pointers
1048 // , including objective-c pointers.
1049 QualType ToPointeeType = ToTypePtr->getPointeeType();
1050 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1051 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1052 ToType, Context);
1053 return true;
1054
1055 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001056 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001057 if (!FromTypePtr)
1058 return false;
1059
1060 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001061
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 // An rvalue of type "pointer to cv T," where T is an object type,
1063 // can be converted to an rvalue of type "pointer to cv void" (C++
1064 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001065 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001066 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001067 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001068 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001069 return true;
1070 }
1071
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001072 // When we're overloading in C, we allow a special kind of pointer
1073 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001074 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001075 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001076 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001077 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001078 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001079 return true;
1080 }
1081
Douglas Gregor5c407d92008-10-23 00:40:37 +00001082 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001083 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001084 // An rvalue of type "pointer to cv D," where D is a class type,
1085 // can be converted to an rvalue of type "pointer to cv B," where
1086 // B is a base class (clause 10) of D. If B is an inaccessible
1087 // (clause 11) or ambiguous (10.2) base class of D, a program that
1088 // necessitates this conversion is ill-formed. The result of the
1089 // conversion is a pointer to the base class sub-object of the
1090 // derived class object. The null pointer value is converted to
1091 // the null pointer value of the destination type.
1092 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001093 // Note that we do not check for ambiguity or inaccessibility
1094 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001095 if (getLangOptions().CPlusPlus &&
1096 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001097 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001098 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001100 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001101 ToType, Context);
1102 return true;
1103 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001104
Douglas Gregora119f102008-12-19 19:13:09 +00001105 return false;
1106}
1107
1108/// isObjCPointerConversion - Determines whether this is an
1109/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1110/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001111bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001112 QualType& ConvertedType,
1113 bool &IncompatibleObjC) {
1114 if (!getLangOptions().ObjC1)
1115 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001116
Steve Naroff7cae42b2009-07-10 23:34:53 +00001117 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001118 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001119 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001120 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001121
Steve Naroff7cae42b2009-07-10 23:34:53 +00001122 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001123 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001124 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001125 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001126 ConvertedType = ToType;
1127 return true;
1128 }
1129 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001130 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001131 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001132 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001133 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001134 ConvertedType = ToType;
1135 return true;
1136 }
1137 // Objective C++: We're able to convert from a pointer to an
1138 // interface to a pointer to a different interface.
1139 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1140 ConvertedType = ToType;
1141 return true;
1142 }
1143
1144 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1145 // Okay: this is some kind of implicit downcast of Objective-C
1146 // interfaces, which is permitted. However, we're going to
1147 // complain about it.
1148 IncompatibleObjC = true;
1149 ConvertedType = FromType;
1150 return true;
1151 }
Mike Stump11289f42009-09-09 15:08:12 +00001152 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001153 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001154 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001155 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001156 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001157 else if (const BlockPointerType *ToBlockPtr =
1158 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001159 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001160 // to a block pointer type.
1161 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1162 ConvertedType = ToType;
1163 return true;
1164 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001165 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001166 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001167 else if (FromType->getAs<BlockPointerType>() &&
1168 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1169 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001170 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001171 ConvertedType = ToType;
1172 return true;
1173 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001174 else
Douglas Gregora119f102008-12-19 19:13:09 +00001175 return false;
1176
Douglas Gregor033f56d2008-12-23 00:53:59 +00001177 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001178 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001179 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001180 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001181 FromPointeeType = FromBlockPtr->getPointeeType();
1182 else
Douglas Gregora119f102008-12-19 19:13:09 +00001183 return false;
1184
Douglas Gregora119f102008-12-19 19:13:09 +00001185 // If we have pointers to pointers, recursively check whether this
1186 // is an Objective-C conversion.
1187 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1188 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1189 IncompatibleObjC)) {
1190 // We always complain about this conversion.
1191 IncompatibleObjC = true;
1192 ConvertedType = ToType;
1193 return true;
1194 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001195 // Allow conversion of pointee being objective-c pointer to another one;
1196 // as in I* to id.
1197 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1198 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1199 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1200 IncompatibleObjC)) {
1201 ConvertedType = ToType;
1202 return true;
1203 }
1204
Douglas Gregor033f56d2008-12-23 00:53:59 +00001205 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001206 // differences in the argument and result types are in Objective-C
1207 // pointer conversions. If so, we permit the conversion (but
1208 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001209 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001210 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001211 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001212 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001213 if (FromFunctionType && ToFunctionType) {
1214 // If the function types are exactly the same, this isn't an
1215 // Objective-C pointer conversion.
1216 if (Context.getCanonicalType(FromPointeeType)
1217 == Context.getCanonicalType(ToPointeeType))
1218 return false;
1219
1220 // Perform the quick checks that will tell us whether these
1221 // function types are obviously different.
1222 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1223 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1224 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1225 return false;
1226
1227 bool HasObjCConversion = false;
1228 if (Context.getCanonicalType(FromFunctionType->getResultType())
1229 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1230 // Okay, the types match exactly. Nothing to do.
1231 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1232 ToFunctionType->getResultType(),
1233 ConvertedType, IncompatibleObjC)) {
1234 // Okay, we have an Objective-C pointer conversion.
1235 HasObjCConversion = true;
1236 } else {
1237 // Function types are too different. Abort.
1238 return false;
1239 }
Mike Stump11289f42009-09-09 15:08:12 +00001240
Douglas Gregora119f102008-12-19 19:13:09 +00001241 // Check argument types.
1242 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1243 ArgIdx != NumArgs; ++ArgIdx) {
1244 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1245 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1246 if (Context.getCanonicalType(FromArgType)
1247 == Context.getCanonicalType(ToArgType)) {
1248 // Okay, the types match exactly. Nothing to do.
1249 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1250 ConvertedType, IncompatibleObjC)) {
1251 // Okay, we have an Objective-C pointer conversion.
1252 HasObjCConversion = true;
1253 } else {
1254 // Argument types are too different. Abort.
1255 return false;
1256 }
1257 }
1258
1259 if (HasObjCConversion) {
1260 // We had an Objective-C conversion. Allow this pointer
1261 // conversion, but complain about it.
1262 ConvertedType = ToType;
1263 IncompatibleObjC = true;
1264 return true;
1265 }
1266 }
1267
Sebastian Redl72b597d2009-01-25 19:43:20 +00001268 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001269}
1270
Douglas Gregor39c16d42008-10-24 04:54:22 +00001271/// CheckPointerConversion - Check the pointer conversion from the
1272/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001273/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001274/// conversions for which IsPointerConversion has already returned
1275/// true. It returns true and produces a diagnostic if there was an
1276/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001277bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001278 CastExpr::CastKind &Kind,
1279 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001280 QualType FromType = From->getType();
1281
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001282 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1283 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001284 QualType FromPointeeType = FromPtrType->getPointeeType(),
1285 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001286
Douglas Gregor39c16d42008-10-24 04:54:22 +00001287 if (FromPointeeType->isRecordType() &&
1288 ToPointeeType->isRecordType()) {
1289 // We must have a derived-to-base conversion. Check an
1290 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001291 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1292 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001293 From->getSourceRange(),
1294 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001295 return true;
1296
1297 // The conversion was successful.
1298 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001299 }
1300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001302 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001303 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001304 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001305 // Objective-C++ conversions are always okay.
1306 // FIXME: We should have a different class of conversions for the
1307 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001308 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001309 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001310
Steve Naroff7cae42b2009-07-10 23:34:53 +00001311 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001312 return false;
1313}
1314
Sebastian Redl72b597d2009-01-25 19:43:20 +00001315/// IsMemberPointerConversion - Determines whether the conversion of the
1316/// expression From, which has the (possibly adjusted) type FromType, can be
1317/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1318/// If so, returns true and places the converted type (that might differ from
1319/// ToType in its cv-qualifiers at some level) into ConvertedType.
1320bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001321 QualType ToType,
1322 bool InOverloadResolution,
1323 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001324 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001325 if (!ToTypePtr)
1326 return false;
1327
1328 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001329 if (From->isNullPointerConstant(Context,
1330 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1331 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001332 ConvertedType = ToType;
1333 return true;
1334 }
1335
1336 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001337 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001338 if (!FromTypePtr)
1339 return false;
1340
1341 // A pointer to member of B can be converted to a pointer to member of D,
1342 // where D is derived from B (C++ 4.11p2).
1343 QualType FromClass(FromTypePtr->getClass(), 0);
1344 QualType ToClass(ToTypePtr->getClass(), 0);
1345 // FIXME: What happens when these are dependent? Is this function even called?
1346
1347 if (IsDerivedFrom(ToClass, FromClass)) {
1348 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1349 ToClass.getTypePtr());
1350 return true;
1351 }
1352
1353 return false;
1354}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001355
Sebastian Redl72b597d2009-01-25 19:43:20 +00001356/// CheckMemberPointerConversion - Check the member pointer conversion from the
1357/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001358/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001359/// for which IsMemberPointerConversion has already returned true. It returns
1360/// true and produces a diagnostic if there was an error, or returns false
1361/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001362bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001363 CastExpr::CastKind &Kind,
1364 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001365 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001367 if (!FromPtrType) {
1368 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001369 assert(From->isNullPointerConstant(Context,
1370 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001371 "Expr must be null pointer constant!");
1372 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001373 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001374 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001375
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001376 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001377 assert(ToPtrType && "No member pointer cast has a target type "
1378 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001379
Sebastian Redled8f2002009-01-28 18:33:18 +00001380 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1381 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001382
Sebastian Redled8f2002009-01-28 18:33:18 +00001383 // FIXME: What about dependent types?
1384 assert(FromClass->isRecordType() && "Pointer into non-class.");
1385 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001386
John McCall5b0829a2010-02-10 09:31:12 +00001387 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001388 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001389 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1390 assert(DerivationOkay &&
1391 "Should not have been called if derivation isn't OK.");
1392 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001393
Sebastian Redled8f2002009-01-28 18:33:18 +00001394 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1395 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001396 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1397 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1398 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1399 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001400 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001401
Douglas Gregor89ee6822009-02-28 01:32:25 +00001402 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001403 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1404 << FromClass << ToClass << QualType(VBase, 0)
1405 << From->getSourceRange();
1406 return true;
1407 }
1408
John McCall5b0829a2010-02-10 09:31:12 +00001409 if (!IgnoreBaseAccess)
1410 CheckBaseClassAccess(From->getExprLoc(), /*BaseToDerived*/ true,
1411 FromClass, ToClass, Paths.front());
1412
Anders Carlssond7923c62009-08-22 23:33:40 +00001413 // Must be a base to derived member conversion.
1414 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001415 return false;
1416}
1417
Douglas Gregor9a657932008-10-21 23:43:52 +00001418/// IsQualificationConversion - Determines whether the conversion from
1419/// an rvalue of type FromType to ToType is a qualification conversion
1420/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001421bool
1422Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001423 FromType = Context.getCanonicalType(FromType);
1424 ToType = Context.getCanonicalType(ToType);
1425
1426 // If FromType and ToType are the same type, this is not a
1427 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001428 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001429 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001430
Douglas Gregor9a657932008-10-21 23:43:52 +00001431 // (C++ 4.4p4):
1432 // A conversion can add cv-qualifiers at levels other than the first
1433 // in multi-level pointers, subject to the following rules: [...]
1434 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001435 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001436 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001437 // Within each iteration of the loop, we check the qualifiers to
1438 // determine if this still looks like a qualification
1439 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001440 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001441 // until there are no more pointers or pointers-to-members left to
1442 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001443 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001444
1445 // -- for every j > 0, if const is in cv 1,j then const is in cv
1446 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001447 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001448 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001449
Douglas Gregor9a657932008-10-21 23:43:52 +00001450 // -- if the cv 1,j and cv 2,j are different, then const is in
1451 // every cv for 0 < k < j.
1452 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001453 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001454 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregor9a657932008-10-21 23:43:52 +00001456 // Keep track of whether all prior cv-qualifiers in the "to" type
1457 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001458 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001459 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001460 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001461
1462 // We are left with FromType and ToType being the pointee types
1463 // after unwrapping the original FromType and ToType the same number
1464 // of types. If we unwrapped any pointers, and if FromType and
1465 // ToType have the same unqualified type (since we checked
1466 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001467 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001468}
1469
Douglas Gregor576e98c2009-01-30 23:27:23 +00001470/// Determines whether there is a user-defined conversion sequence
1471/// (C++ [over.ics.user]) that converts expression From to the type
1472/// ToType. If such a conversion exists, User will contain the
1473/// user-defined conversion sequence that performs such a conversion
1474/// and this routine will return true. Otherwise, this routine returns
1475/// false and User is unspecified.
1476///
1477/// \param AllowConversionFunctions true if the conversion should
1478/// consider conversion functions at all. If false, only constructors
1479/// will be considered.
1480///
1481/// \param AllowExplicit true if the conversion should consider C++0x
1482/// "explicit" conversion functions as well as non-explicit conversion
1483/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001484///
1485/// \param ForceRValue true if the expression should be treated as an rvalue
1486/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001487/// \param UserCast true if looking for user defined conversion for a static
1488/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001489OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1490 UserDefinedConversionSequence& User,
1491 OverloadCandidateSet& CandidateSet,
1492 bool AllowConversionFunctions,
1493 bool AllowExplicit,
1494 bool ForceRValue,
1495 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001496 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001497 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1498 // We're not going to find any constructors.
1499 } else if (CXXRecordDecl *ToRecordDecl
1500 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001501 // C++ [over.match.ctor]p1:
1502 // When objects of class type are direct-initialized (8.5), or
1503 // copy-initialized from an expression of the same or a
1504 // derived class type (8.5), overload resolution selects the
1505 // constructor. [...] For copy-initialization, the candidate
1506 // functions are all the converting constructors (12.3.1) of
1507 // that class. The argument list is the expression-list within
1508 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001509 bool SuppressUserConversions = !UserCast;
1510 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1511 IsDerivedFrom(From->getType(), ToType)) {
1512 SuppressUserConversions = false;
1513 AllowConversionFunctions = false;
1514 }
1515
Mike Stump11289f42009-09-09 15:08:12 +00001516 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001517 = Context.DeclarationNames.getCXXConstructorName(
1518 Context.getCanonicalType(ToType).getUnqualifiedType());
1519 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001520 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001521 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001522 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001523 // Find the constructor (which may be a template).
1524 CXXConstructorDecl *Constructor = 0;
1525 FunctionTemplateDecl *ConstructorTmpl
1526 = dyn_cast<FunctionTemplateDecl>(*Con);
1527 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001528 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001529 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1530 else
1531 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001532
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001533 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001534 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001535 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00001536 AddTemplateOverloadCandidate(ConstructorTmpl,
1537 ConstructorTmpl->getAccess(),
1538 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001539 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001540 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001541 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001542 // Allow one user-defined conversion when user specifies a
1543 // From->ToType conversion via an static cast (c-style, etc).
John McCallb89836b2010-01-26 01:37:31 +00001544 AddOverloadCandidate(Constructor, Constructor->getAccess(),
1545 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001546 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001547 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001548 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001549 }
1550 }
1551
Douglas Gregor576e98c2009-01-30 23:27:23 +00001552 if (!AllowConversionFunctions) {
1553 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001554 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1555 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001556 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001557 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001558 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001559 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001560 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001561 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1562 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001563 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001564 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001565 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001566 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001567 NamedDecl *D = *I;
1568 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1569 if (isa<UsingShadowDecl>(D))
1570 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1571
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001572 CXXConversionDecl *Conv;
1573 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001574 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001575 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1576 else
John McCalld14a8642009-11-21 08:51:07 +00001577 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001578
1579 if (AllowExplicit || !Conv->isExplicit()) {
1580 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00001581 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
1582 ActingContext, From, ToType,
1583 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001584 else
John McCallb89836b2010-01-26 01:37:31 +00001585 AddConversionCandidate(Conv, I.getAccess(), ActingContext,
1586 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001587 }
1588 }
1589 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001590 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001591
1592 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001593 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001594 case OR_Success:
1595 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001596 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001597 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1598 // C++ [over.ics.user]p1:
1599 // If the user-defined conversion is specified by a
1600 // constructor (12.3.1), the initial standard conversion
1601 // sequence converts the source type to the type required by
1602 // the argument of the constructor.
1603 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001604 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001605 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001606 User.EllipsisConversion = true;
1607 else {
1608 User.Before = Best->Conversions[0].Standard;
1609 User.EllipsisConversion = false;
1610 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001611 User.ConversionFunction = Constructor;
1612 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001613 User.After.setFromType(
1614 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001615 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001616 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001617 } else if (CXXConversionDecl *Conversion
1618 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1619 // C++ [over.ics.user]p1:
1620 //
1621 // [...] If the user-defined conversion is specified by a
1622 // conversion function (12.3.2), the initial standard
1623 // conversion sequence converts the source type to the
1624 // implicit object parameter of the conversion function.
1625 User.Before = Best->Conversions[0].Standard;
1626 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001627 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001628
1629 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001630 // The second standard conversion sequence converts the
1631 // result of the user-defined conversion to the target type
1632 // for the sequence. Since an implicit conversion sequence
1633 // is an initialization, the special rules for
1634 // initialization by user-defined conversion apply when
1635 // selecting the best user-defined conversion for a
1636 // user-defined conversion sequence (see 13.3.3 and
1637 // 13.3.3.1).
1638 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001639 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001640 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001641 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001642 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001643 }
Mike Stump11289f42009-09-09 15:08:12 +00001644
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001646 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001647 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001648 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001649 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001650
1651 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001652 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001653 }
1654
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001655 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001656}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001657
1658bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001659Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001660 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001661 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001662 OverloadingResult OvResult =
1663 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1664 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001665 if (OvResult == OR_Ambiguous)
1666 Diag(From->getSourceRange().getBegin(),
1667 diag::err_typecheck_ambiguous_condition)
1668 << From->getType() << ToType << From->getSourceRange();
1669 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1670 Diag(From->getSourceRange().getBegin(),
1671 diag::err_typecheck_nonviable_condition)
1672 << From->getType() << ToType << From->getSourceRange();
1673 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001674 return false;
John McCallad907772010-01-12 07:18:19 +00001675 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001676 return true;
1677}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001678
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001679/// CompareImplicitConversionSequences - Compare two implicit
1680/// conversion sequences to determine whether one is better than the
1681/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001682ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1684 const ImplicitConversionSequence& ICS2)
1685{
1686 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1687 // conversion sequences (as defined in 13.3.3.1)
1688 // -- a standard conversion sequence (13.3.3.1.1) is a better
1689 // conversion sequence than a user-defined conversion sequence or
1690 // an ellipsis conversion sequence, and
1691 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1692 // conversion sequence than an ellipsis conversion sequence
1693 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001694 //
John McCall0d1da222010-01-12 00:44:57 +00001695 // C++0x [over.best.ics]p10:
1696 // For the purpose of ranking implicit conversion sequences as
1697 // described in 13.3.3.2, the ambiguous conversion sequence is
1698 // treated as a user-defined sequence that is indistinguishable
1699 // from any other user-defined conversion sequence.
1700 if (ICS1.getKind() < ICS2.getKind()) {
1701 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1702 return ImplicitConversionSequence::Better;
1703 } else if (ICS2.getKind() < ICS1.getKind()) {
1704 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1705 return ImplicitConversionSequence::Worse;
1706 }
1707
1708 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1709 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710
1711 // Two implicit conversion sequences of the same form are
1712 // indistinguishable conversion sequences unless one of the
1713 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001714 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001716 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717 // User-defined conversion sequence U1 is a better conversion
1718 // sequence than another user-defined conversion sequence U2 if
1719 // they contain the same user-defined conversion function or
1720 // constructor and if the second standard conversion sequence of
1721 // U1 is better than the second standard conversion sequence of
1722 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001723 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724 ICS2.UserDefined.ConversionFunction)
1725 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1726 ICS2.UserDefined.After);
1727 }
1728
1729 return ImplicitConversionSequence::Indistinguishable;
1730}
1731
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001732// Per 13.3.3.2p3, compare the given standard conversion sequences to
1733// determine if one is a proper subset of the other.
1734static ImplicitConversionSequence::CompareKind
1735compareStandardConversionSubsets(ASTContext &Context,
1736 const StandardConversionSequence& SCS1,
1737 const StandardConversionSequence& SCS2) {
1738 ImplicitConversionSequence::CompareKind Result
1739 = ImplicitConversionSequence::Indistinguishable;
1740
1741 if (SCS1.Second != SCS2.Second) {
1742 if (SCS1.Second == ICK_Identity)
1743 Result = ImplicitConversionSequence::Better;
1744 else if (SCS2.Second == ICK_Identity)
1745 Result = ImplicitConversionSequence::Worse;
1746 else
1747 return ImplicitConversionSequence::Indistinguishable;
1748 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1749 return ImplicitConversionSequence::Indistinguishable;
1750
1751 if (SCS1.Third == SCS2.Third) {
1752 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1753 : ImplicitConversionSequence::Indistinguishable;
1754 }
1755
1756 if (SCS1.Third == ICK_Identity)
1757 return Result == ImplicitConversionSequence::Worse
1758 ? ImplicitConversionSequence::Indistinguishable
1759 : ImplicitConversionSequence::Better;
1760
1761 if (SCS2.Third == ICK_Identity)
1762 return Result == ImplicitConversionSequence::Better
1763 ? ImplicitConversionSequence::Indistinguishable
1764 : ImplicitConversionSequence::Worse;
1765
1766 return ImplicitConversionSequence::Indistinguishable;
1767}
1768
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001769/// CompareStandardConversionSequences - Compare two standard
1770/// conversion sequences to determine whether one is better than the
1771/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001772ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001773Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1774 const StandardConversionSequence& SCS2)
1775{
1776 // Standard conversion sequence S1 is a better conversion sequence
1777 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1778
1779 // -- S1 is a proper subsequence of S2 (comparing the conversion
1780 // sequences in the canonical form defined by 13.3.3.1.1,
1781 // excluding any Lvalue Transformation; the identity conversion
1782 // sequence is considered to be a subsequence of any
1783 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001784 if (ImplicitConversionSequence::CompareKind CK
1785 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1786 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001787
1788 // -- the rank of S1 is better than the rank of S2 (by the rules
1789 // defined below), or, if not that,
1790 ImplicitConversionRank Rank1 = SCS1.getRank();
1791 ImplicitConversionRank Rank2 = SCS2.getRank();
1792 if (Rank1 < Rank2)
1793 return ImplicitConversionSequence::Better;
1794 else if (Rank2 < Rank1)
1795 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001796
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001797 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1798 // are indistinguishable unless one of the following rules
1799 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001800
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001801 // A conversion that is not a conversion of a pointer, or
1802 // pointer to member, to bool is better than another conversion
1803 // that is such a conversion.
1804 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1805 return SCS2.isPointerConversionToBool()
1806 ? ImplicitConversionSequence::Better
1807 : ImplicitConversionSequence::Worse;
1808
Douglas Gregor5c407d92008-10-23 00:40:37 +00001809 // C++ [over.ics.rank]p4b2:
1810 //
1811 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001812 // conversion of B* to A* is better than conversion of B* to
1813 // void*, and conversion of A* to void* is better than conversion
1814 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001815 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001816 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001817 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001818 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001819 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1820 // Exactly one of the conversion sequences is a conversion to
1821 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001822 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1823 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001824 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1825 // Neither conversion sequence converts to a void pointer; compare
1826 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001827 if (ImplicitConversionSequence::CompareKind DerivedCK
1828 = CompareDerivedToBaseConversions(SCS1, SCS2))
1829 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001830 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1831 // Both conversion sequences are conversions to void
1832 // pointers. Compare the source types to determine if there's an
1833 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001834 QualType FromType1 = SCS1.getFromType();
1835 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001836
1837 // Adjust the types we're converting from via the array-to-pointer
1838 // conversion, if we need to.
1839 if (SCS1.First == ICK_Array_To_Pointer)
1840 FromType1 = Context.getArrayDecayedType(FromType1);
1841 if (SCS2.First == ICK_Array_To_Pointer)
1842 FromType2 = Context.getArrayDecayedType(FromType2);
1843
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001844 QualType FromPointee1
1845 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1846 QualType FromPointee2
1847 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001848
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001849 if (IsDerivedFrom(FromPointee2, FromPointee1))
1850 return ImplicitConversionSequence::Better;
1851 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1852 return ImplicitConversionSequence::Worse;
1853
1854 // Objective-C++: If one interface is more specific than the
1855 // other, it is the better one.
1856 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1857 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1858 if (FromIface1 && FromIface1) {
1859 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1860 return ImplicitConversionSequence::Better;
1861 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1862 return ImplicitConversionSequence::Worse;
1863 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001864 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001865
1866 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1867 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001868 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001869 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001870 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001871
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001872 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001873 // C++0x [over.ics.rank]p3b4:
1874 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1875 // implicit object parameter of a non-static member function declared
1876 // without a ref-qualifier, and S1 binds an rvalue reference to an
1877 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001878 // FIXME: We don't know if we're dealing with the implicit object parameter,
1879 // or if the member function in this case has a ref qualifier.
1880 // (Of course, we don't have ref qualifiers yet.)
1881 if (SCS1.RRefBinding != SCS2.RRefBinding)
1882 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1883 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001884
1885 // C++ [over.ics.rank]p3b4:
1886 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1887 // which the references refer are the same type except for
1888 // top-level cv-qualifiers, and the type to which the reference
1889 // initialized by S2 refers is more cv-qualified than the type
1890 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001891 QualType T1 = SCS1.getToType(2);
1892 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001893 T1 = Context.getCanonicalType(T1);
1894 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001895 Qualifiers T1Quals, T2Quals;
1896 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1897 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1898 if (UnqualT1 == UnqualT2) {
1899 // If the type is an array type, promote the element qualifiers to the type
1900 // for comparison.
1901 if (isa<ArrayType>(T1) && T1Quals)
1902 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1903 if (isa<ArrayType>(T2) && T2Quals)
1904 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001905 if (T2.isMoreQualifiedThan(T1))
1906 return ImplicitConversionSequence::Better;
1907 else if (T1.isMoreQualifiedThan(T2))
1908 return ImplicitConversionSequence::Worse;
1909 }
1910 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001911
1912 return ImplicitConversionSequence::Indistinguishable;
1913}
1914
1915/// CompareQualificationConversions - Compares two standard conversion
1916/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001917/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1918ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001919Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001920 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001921 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001922 // -- S1 and S2 differ only in their qualification conversion and
1923 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1924 // cv-qualification signature of type T1 is a proper subset of
1925 // the cv-qualification signature of type T2, and S1 is not the
1926 // deprecated string literal array-to-pointer conversion (4.2).
1927 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1928 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1929 return ImplicitConversionSequence::Indistinguishable;
1930
1931 // FIXME: the example in the standard doesn't use a qualification
1932 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001933 QualType T1 = SCS1.getToType(2);
1934 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001935 T1 = Context.getCanonicalType(T1);
1936 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001937 Qualifiers T1Quals, T2Quals;
1938 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1939 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001940
1941 // If the types are the same, we won't learn anything by unwrapped
1942 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001943 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001944 return ImplicitConversionSequence::Indistinguishable;
1945
Chandler Carruth607f38e2009-12-29 07:16:59 +00001946 // If the type is an array type, promote the element qualifiers to the type
1947 // for comparison.
1948 if (isa<ArrayType>(T1) && T1Quals)
1949 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1950 if (isa<ArrayType>(T2) && T2Quals)
1951 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1952
Mike Stump11289f42009-09-09 15:08:12 +00001953 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001954 = ImplicitConversionSequence::Indistinguishable;
1955 while (UnwrapSimilarPointerTypes(T1, T2)) {
1956 // Within each iteration of the loop, we check the qualifiers to
1957 // determine if this still looks like a qualification
1958 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001959 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001960 // until there are no more pointers or pointers-to-members left
1961 // to unwrap. This essentially mimics what
1962 // IsQualificationConversion does, but here we're checking for a
1963 // strict subset of qualifiers.
1964 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1965 // The qualifiers are the same, so this doesn't tell us anything
1966 // about how the sequences rank.
1967 ;
1968 else if (T2.isMoreQualifiedThan(T1)) {
1969 // T1 has fewer qualifiers, so it could be the better sequence.
1970 if (Result == ImplicitConversionSequence::Worse)
1971 // Neither has qualifiers that are a subset of the other's
1972 // qualifiers.
1973 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001974
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001975 Result = ImplicitConversionSequence::Better;
1976 } else if (T1.isMoreQualifiedThan(T2)) {
1977 // T2 has fewer qualifiers, so it could be the better sequence.
1978 if (Result == ImplicitConversionSequence::Better)
1979 // Neither has qualifiers that are a subset of the other's
1980 // qualifiers.
1981 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001982
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001983 Result = ImplicitConversionSequence::Worse;
1984 } else {
1985 // Qualifiers are disjoint.
1986 return ImplicitConversionSequence::Indistinguishable;
1987 }
1988
1989 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001990 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001991 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001992 }
1993
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001994 // Check that the winning standard conversion sequence isn't using
1995 // the deprecated string literal array to pointer conversion.
1996 switch (Result) {
1997 case ImplicitConversionSequence::Better:
1998 if (SCS1.Deprecated)
1999 Result = ImplicitConversionSequence::Indistinguishable;
2000 break;
2001
2002 case ImplicitConversionSequence::Indistinguishable:
2003 break;
2004
2005 case ImplicitConversionSequence::Worse:
2006 if (SCS2.Deprecated)
2007 Result = ImplicitConversionSequence::Indistinguishable;
2008 break;
2009 }
2010
2011 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002012}
2013
Douglas Gregor5c407d92008-10-23 00:40:37 +00002014/// CompareDerivedToBaseConversions - Compares two standard conversion
2015/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002016/// various kinds of derived-to-base conversions (C++
2017/// [over.ics.rank]p4b3). As part of these checks, we also look at
2018/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002019ImplicitConversionSequence::CompareKind
2020Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2021 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002022 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002023 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002024 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002025 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002026
2027 // Adjust the types we're converting from via the array-to-pointer
2028 // conversion, if we need to.
2029 if (SCS1.First == ICK_Array_To_Pointer)
2030 FromType1 = Context.getArrayDecayedType(FromType1);
2031 if (SCS2.First == ICK_Array_To_Pointer)
2032 FromType2 = Context.getArrayDecayedType(FromType2);
2033
2034 // Canonicalize all of the types.
2035 FromType1 = Context.getCanonicalType(FromType1);
2036 ToType1 = Context.getCanonicalType(ToType1);
2037 FromType2 = Context.getCanonicalType(FromType2);
2038 ToType2 = Context.getCanonicalType(ToType2);
2039
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002040 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002041 //
2042 // If class B is derived directly or indirectly from class A and
2043 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002044 //
2045 // For Objective-C, we let A, B, and C also be Objective-C
2046 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002047
2048 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002049 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002050 SCS2.Second == ICK_Pointer_Conversion &&
2051 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2052 FromType1->isPointerType() && FromType2->isPointerType() &&
2053 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002054 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002055 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002056 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002057 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002058 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002059 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002060 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002061 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002062
John McCall9dd450b2009-09-21 23:43:11 +00002063 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2064 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2065 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2066 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002067
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002068 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002069 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2070 if (IsDerivedFrom(ToPointee1, ToPointee2))
2071 return ImplicitConversionSequence::Better;
2072 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2073 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002074
2075 if (ToIface1 && ToIface2) {
2076 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2077 return ImplicitConversionSequence::Better;
2078 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2079 return ImplicitConversionSequence::Worse;
2080 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002081 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002082
2083 // -- conversion of B* to A* is better than conversion of C* to A*,
2084 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2085 if (IsDerivedFrom(FromPointee2, FromPointee1))
2086 return ImplicitConversionSequence::Better;
2087 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2088 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002089
Douglas Gregor237f96c2008-11-26 23:31:11 +00002090 if (FromIface1 && FromIface2) {
2091 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2092 return ImplicitConversionSequence::Better;
2093 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2094 return ImplicitConversionSequence::Worse;
2095 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002096 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002097 }
2098
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002099 // Compare based on reference bindings.
2100 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2101 SCS1.Second == ICK_Derived_To_Base) {
2102 // -- binding of an expression of type C to a reference of type
2103 // B& is better than binding an expression of type C to a
2104 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002105 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2106 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002107 if (IsDerivedFrom(ToType1, ToType2))
2108 return ImplicitConversionSequence::Better;
2109 else if (IsDerivedFrom(ToType2, ToType1))
2110 return ImplicitConversionSequence::Worse;
2111 }
2112
Douglas Gregor2fe98832008-11-03 19:09:14 +00002113 // -- binding of an expression of type B to a reference of type
2114 // A& is better than binding an expression of type C to a
2115 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002116 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2117 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002118 if (IsDerivedFrom(FromType2, FromType1))
2119 return ImplicitConversionSequence::Better;
2120 else if (IsDerivedFrom(FromType1, FromType2))
2121 return ImplicitConversionSequence::Worse;
2122 }
2123 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002124
2125 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002126 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2127 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2128 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2129 const MemberPointerType * FromMemPointer1 =
2130 FromType1->getAs<MemberPointerType>();
2131 const MemberPointerType * ToMemPointer1 =
2132 ToType1->getAs<MemberPointerType>();
2133 const MemberPointerType * FromMemPointer2 =
2134 FromType2->getAs<MemberPointerType>();
2135 const MemberPointerType * ToMemPointer2 =
2136 ToType2->getAs<MemberPointerType>();
2137 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2138 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2139 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2140 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2141 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2142 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2143 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2144 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002145 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002146 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2147 if (IsDerivedFrom(ToPointee1, ToPointee2))
2148 return ImplicitConversionSequence::Worse;
2149 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2150 return ImplicitConversionSequence::Better;
2151 }
2152 // conversion of B::* to C::* is better than conversion of A::* to C::*
2153 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2154 if (IsDerivedFrom(FromPointee1, FromPointee2))
2155 return ImplicitConversionSequence::Better;
2156 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2157 return ImplicitConversionSequence::Worse;
2158 }
2159 }
2160
Douglas Gregor2fe98832008-11-03 19:09:14 +00002161 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2162 SCS1.Second == ICK_Derived_To_Base) {
2163 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002164 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2165 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002166 if (IsDerivedFrom(ToType1, ToType2))
2167 return ImplicitConversionSequence::Better;
2168 else if (IsDerivedFrom(ToType2, ToType1))
2169 return ImplicitConversionSequence::Worse;
2170 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002171
Douglas Gregor2fe98832008-11-03 19:09:14 +00002172 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002173 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2174 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002175 if (IsDerivedFrom(FromType2, FromType1))
2176 return ImplicitConversionSequence::Better;
2177 else if (IsDerivedFrom(FromType1, FromType2))
2178 return ImplicitConversionSequence::Worse;
2179 }
2180 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002181
Douglas Gregor5c407d92008-10-23 00:40:37 +00002182 return ImplicitConversionSequence::Indistinguishable;
2183}
2184
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002185/// TryCopyInitialization - Try to copy-initialize a value of type
2186/// ToType from the expression From. Return the implicit conversion
2187/// sequence required to pass this argument, which may be a bad
2188/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002189/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002190/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2191/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002192ImplicitConversionSequence
2193Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002194 bool SuppressUserConversions, bool ForceRValue,
2195 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002196 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002197 ImplicitConversionSequence ICS;
John McCall6a61b522010-01-13 09:16:55 +00002198 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002199 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002200 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002201 SuppressUserConversions,
2202 /*AllowExplicit=*/false,
2203 ForceRValue,
2204 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002205 return ICS;
2206 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002207 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002208 SuppressUserConversions,
2209 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002210 ForceRValue,
2211 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002212 }
2213}
2214
Sebastian Redl42e92c42009-04-12 17:16:29 +00002215/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2216/// the expression @p From. Returns true (and emits a diagnostic) if there was
2217/// an error, returns false if the initialization succeeded. Elidable should
2218/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2219/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002220bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002221 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002222 if (!getLangOptions().CPlusPlus) {
2223 // In C, argument passing is the same as performing an assignment.
2224 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002225
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002226 AssignConvertType ConvTy =
2227 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002228 if (ConvTy != Compatible &&
2229 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2230 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002231
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002232 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002233 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002234 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002235
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002236 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002237 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002238 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002239 /*SuppressUserConversions=*/false,
2240 /*AllowExplicit=*/false,
2241 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002242
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002243 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002244 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002245 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002246 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002247 return Diag(From->getSourceRange().getBegin(),
2248 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002249 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002250 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002251}
2252
Douglas Gregor436424c2008-11-18 23:14:02 +00002253/// TryObjectArgumentInitialization - Try to initialize the object
2254/// parameter of the given member function (@c Method) from the
2255/// expression @p From.
2256ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002257Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002258 CXXMethodDecl *Method,
2259 CXXRecordDecl *ActingContext) {
2260 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002261 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2262 // const volatile object.
2263 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2264 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2265 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002266
2267 // Set up the conversion sequence as a "bad" conversion, to allow us
2268 // to exit early.
2269 ImplicitConversionSequence ICS;
2270 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002271 ICS.setBad();
Douglas Gregor436424c2008-11-18 23:14:02 +00002272
2273 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002274 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002275 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002276 FromType = PT->getPointeeType();
2277
2278 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002279
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002280 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002281 // where X is the class of which the function is a member
2282 // (C++ [over.match.funcs]p4). However, when finding an implicit
2283 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002284 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002285 // (C++ [over.match.funcs]p5). We perform a simplified version of
2286 // reference binding here, that allows class rvalues to bind to
2287 // non-constant references.
2288
2289 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2290 // with the implicit object parameter (C++ [over.match.funcs]p5).
2291 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002292 if (ImplicitParamType.getCVRQualifiers()
2293 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002294 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall47000992010-01-14 03:28:57 +00002295 ICS.Bad.init(BadConversionSequence::bad_qualifiers,
2296 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002297 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002298 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002299
2300 // Check that we have either the same type or a derived type. It
2301 // affects the conversion rank.
2302 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002303 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002304 ICS.Standard.Second = ICK_Identity;
2305 else if (IsDerivedFrom(FromType, ClassType))
2306 ICS.Standard.Second = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002307 else {
2308 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002309 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002310 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002311
2312 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002313 ICS.setStandard();
2314 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() &&
2442 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2443 return;
2444 }
2445
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002446 // Add this candidate
2447 CandidateSet.push_back(OverloadCandidate());
2448 OverloadCandidate& Candidate = CandidateSet.back();
2449 Candidate.Function = Function;
John McCallb89836b2010-01-26 01:37:31 +00002450 Candidate.Access = Access;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002451 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002452 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002453 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002454
2455 unsigned NumArgsInProto = Proto->getNumArgs();
2456
2457 // (C++ 13.3.2p2): A candidate function having fewer than m
2458 // parameters is viable only if it has an ellipsis in its parameter
2459 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002460 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2461 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002462 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002463 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002464 return;
2465 }
2466
2467 // (C++ 13.3.2p2): A candidate function having more than m parameters
2468 // is viable only if the (m+1)st parameter has a default argument
2469 // (8.3.6). For the purposes of overload resolution, the
2470 // parameter list is truncated on the right, so that there are
2471 // exactly m parameters.
2472 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002473 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002474 // Not enough arguments.
2475 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002476 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002477 return;
2478 }
2479
2480 // Determine the implicit conversion sequences for each of the
2481 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002482 Candidate.Conversions.resize(NumArgs);
2483 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2484 if (ArgIdx < NumArgsInProto) {
2485 // (C++ 13.3.2p3): for F to be a viable function, there shall
2486 // exist for each argument an implicit conversion sequence
2487 // (13.3.3.1) that converts that argument to the corresponding
2488 // parameter of F.
2489 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002490 Candidate.Conversions[ArgIdx]
2491 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002492 SuppressUserConversions, ForceRValue,
2493 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002494 if (Candidate.Conversions[ArgIdx].isBad()) {
2495 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002496 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002497 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002498 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002499 } else {
2500 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2501 // argument for which there is no corresponding parameter is
2502 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002503 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002504 }
2505 }
2506}
2507
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002508/// \brief Add all of the function declarations in the given function set to
2509/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002510void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002511 Expr **Args, unsigned NumArgs,
2512 OverloadCandidateSet& CandidateSet,
2513 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002514 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002515 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002516 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2517 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002518 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002519 cast<CXXMethodDecl>(FD)->getParent(),
2520 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002521 CandidateSet, SuppressUserConversions);
2522 else
John McCallb89836b2010-01-26 01:37:31 +00002523 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002524 SuppressUserConversions);
2525 } else {
2526 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2527 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2528 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002529 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002530 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002531 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002532 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002533 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002534 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002535 else
John McCallb89836b2010-01-26 01:37:31 +00002536 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCall6b51f282009-11-23 01:53:49 +00002537 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002538 Args, NumArgs, CandidateSet,
2539 SuppressUserConversions);
2540 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002541 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002542}
2543
John McCallf0f1cf02009-11-17 07:50:12 +00002544/// AddMethodCandidate - Adds a named decl (which is some kind of
2545/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002546void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCallb89836b2010-01-26 01:37:31 +00002547 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002548 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002549 Expr **Args, unsigned NumArgs,
2550 OverloadCandidateSet& CandidateSet,
2551 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002552 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002553
2554 if (isa<UsingShadowDecl>(Decl))
2555 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2556
2557 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2558 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2559 "Expected a member function template");
John McCallb89836b2010-01-26 01:37:31 +00002560 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002561 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002562 CandidateSet,
2563 SuppressUserConversions,
2564 ForceRValue);
2565 } else {
John McCallb89836b2010-01-26 01:37:31 +00002566 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002567 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002568 CandidateSet, SuppressUserConversions, ForceRValue);
2569 }
2570}
2571
Douglas Gregor436424c2008-11-18 23:14:02 +00002572/// AddMethodCandidate - Adds the given C++ member function to the set
2573/// of candidate functions, using the given function call arguments
2574/// and the object argument (@c Object). For example, in a call
2575/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2576/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2577/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002578/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2579/// a slightly hacky way to implement the overloading rules for elidable copy
2580/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002581void
John McCallb89836b2010-01-26 01:37:31 +00002582Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2583 CXXRecordDecl *ActingContext, QualType ObjectType,
2584 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002585 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002586 bool SuppressUserConversions, bool ForceRValue) {
2587 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002588 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002589 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002590 assert(!isa<CXXConstructorDecl>(Method) &&
2591 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002592
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002593 if (!CandidateSet.isNewCandidate(Method))
2594 return;
2595
Douglas Gregor27381f32009-11-23 12:27:39 +00002596 // Overload resolution is always an unevaluated context.
2597 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2598
Douglas Gregor436424c2008-11-18 23:14:02 +00002599 // Add this candidate
2600 CandidateSet.push_back(OverloadCandidate());
2601 OverloadCandidate& Candidate = CandidateSet.back();
2602 Candidate.Function = Method;
John McCallb89836b2010-01-26 01:37:31 +00002603 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002604 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002605 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002606
2607 unsigned NumArgsInProto = Proto->getNumArgs();
2608
2609 // (C++ 13.3.2p2): A candidate function having fewer than m
2610 // parameters is viable only if it has an ellipsis in its parameter
2611 // list (8.3.5).
2612 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2613 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002614 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002615 return;
2616 }
2617
2618 // (C++ 13.3.2p2): A candidate function having more than m parameters
2619 // is viable only if the (m+1)st parameter has a default argument
2620 // (8.3.6). For the purposes of overload resolution, the
2621 // parameter list is truncated on the right, so that there are
2622 // exactly m parameters.
2623 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2624 if (NumArgs < MinRequiredArgs) {
2625 // Not enough arguments.
2626 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002627 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002628 return;
2629 }
2630
2631 Candidate.Viable = true;
2632 Candidate.Conversions.resize(NumArgs + 1);
2633
John McCall6e9f8f62009-12-03 04:06:58 +00002634 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002635 // The implicit object argument is ignored.
2636 Candidate.IgnoreObjectArgument = true;
2637 else {
2638 // Determine the implicit conversion sequence for the object
2639 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002640 Candidate.Conversions[0]
2641 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002642 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002643 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002644 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002645 return;
2646 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002647 }
2648
2649 // Determine the implicit conversion sequences for each of the
2650 // arguments.
2651 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2652 if (ArgIdx < NumArgsInProto) {
2653 // (C++ 13.3.2p3): for F to be a viable function, there shall
2654 // exist for each argument an implicit conversion sequence
2655 // (13.3.3.1) that converts that argument to the corresponding
2656 // parameter of F.
2657 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002658 Candidate.Conversions[ArgIdx + 1]
2659 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002660 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002661 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002662 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002663 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002664 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002665 break;
2666 }
2667 } else {
2668 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2669 // argument for which there is no corresponding parameter is
2670 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002671 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002672 }
2673 }
2674}
2675
Douglas Gregor97628d62009-08-21 00:16:32 +00002676/// \brief Add a C++ member function template as a candidate to the candidate
2677/// set, using template argument deduction to produce an appropriate member
2678/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002679void
Douglas Gregor97628d62009-08-21 00:16:32 +00002680Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCallb89836b2010-01-26 01:37:31 +00002681 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002682 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002683 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002684 QualType ObjectType,
2685 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002686 OverloadCandidateSet& CandidateSet,
2687 bool SuppressUserConversions,
2688 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002689 if (!CandidateSet.isNewCandidate(MethodTmpl))
2690 return;
2691
Douglas Gregor97628d62009-08-21 00:16:32 +00002692 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002693 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002694 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002695 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002696 // candidate functions in the usual way.113) A given name can refer to one
2697 // or more function templates and also to a set of overloaded non-template
2698 // functions. In such a case, the candidate functions generated from each
2699 // function template are combined with the set of non-template candidate
2700 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002701 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00002702 FunctionDecl *Specialization = 0;
2703 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002704 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002705 Args, NumArgs, Specialization, Info)) {
2706 // FIXME: Record what happened with template argument deduction, so
2707 // that we can give the user a beautiful diagnostic.
2708 (void)Result;
2709 return;
2710 }
Mike Stump11289f42009-09-09 15:08:12 +00002711
Douglas Gregor97628d62009-08-21 00:16:32 +00002712 // Add the function template specialization produced by template argument
2713 // deduction as a candidate.
2714 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002715 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002716 "Specialization is not a member function?");
John McCallb89836b2010-01-26 01:37:31 +00002717 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2718 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002719 CandidateSet, SuppressUserConversions, ForceRValue);
2720}
2721
Douglas Gregor05155d82009-08-21 23:19:43 +00002722/// \brief Add a C++ function template specialization as a candidate
2723/// in the candidate set, using template argument deduction to produce
2724/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002725void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002726Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002727 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00002728 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002729 Expr **Args, unsigned NumArgs,
2730 OverloadCandidateSet& CandidateSet,
2731 bool SuppressUserConversions,
2732 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002733 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2734 return;
2735
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002736 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002737 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002738 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002739 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002740 // candidate functions in the usual way.113) A given name can refer to one
2741 // or more function templates and also to a set of overloaded non-template
2742 // functions. In such a case, the candidate functions generated from each
2743 // function template are combined with the set of non-template candidate
2744 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002745 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002746 FunctionDecl *Specialization = 0;
2747 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002748 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002749 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00002750 CandidateSet.push_back(OverloadCandidate());
2751 OverloadCandidate &Candidate = CandidateSet.back();
2752 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCallb89836b2010-01-26 01:37:31 +00002753 Candidate.Access = Access;
John McCalld681c392009-12-16 08:11:27 +00002754 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002755 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002756 Candidate.IsSurrogate = false;
2757 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00002758
2759 // TODO: record more information about failed template arguments
2760 Candidate.DeductionFailure.Result = Result;
2761 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002762 return;
2763 }
Mike Stump11289f42009-09-09 15:08:12 +00002764
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002765 // Add the function template specialization produced by template argument
2766 // deduction as a candidate.
2767 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002768 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002769 SuppressUserConversions, ForceRValue);
2770}
Mike Stump11289f42009-09-09 15:08:12 +00002771
Douglas Gregora1f013e2008-11-07 22:36:19 +00002772/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002773/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002774/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002775/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002776/// (which may or may not be the same type as the type that the
2777/// conversion function produces).
2778void
2779Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002780 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002781 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002782 Expr *From, QualType ToType,
2783 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002784 assert(!Conversion->getDescribedFunctionTemplate() &&
2785 "Conversion function templates use AddTemplateConversionCandidate");
2786
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002787 if (!CandidateSet.isNewCandidate(Conversion))
2788 return;
2789
Douglas Gregor27381f32009-11-23 12:27:39 +00002790 // Overload resolution is always an unevaluated context.
2791 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2792
Douglas Gregora1f013e2008-11-07 22:36:19 +00002793 // Add this candidate
2794 CandidateSet.push_back(OverloadCandidate());
2795 OverloadCandidate& Candidate = CandidateSet.back();
2796 Candidate.Function = Conversion;
John McCallb89836b2010-01-26 01:37:31 +00002797 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002798 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002799 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002800 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002801 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002802 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002803
Douglas Gregor436424c2008-11-18 23:14:02 +00002804 // Determine the implicit conversion sequence for the implicit
2805 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002806 Candidate.Viable = true;
2807 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002808 Candidate.Conversions[0]
2809 = TryObjectArgumentInitialization(From->getType(), Conversion,
2810 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002811 // Conversion functions to a different type in the base class is visible in
2812 // the derived class. So, a derived to base conversion should not participate
2813 // in overload resolution.
2814 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2815 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002816 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002817 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002818 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002819 return;
2820 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002821
2822 // We won't go through a user-define type conversion function to convert a
2823 // derived to base as such conversions are given Conversion Rank. They only
2824 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2825 QualType FromCanon
2826 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2827 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2828 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2829 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002830 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002831 return;
2832 }
2833
Douglas Gregora1f013e2008-11-07 22:36:19 +00002834
2835 // To determine what the conversion from the result of calling the
2836 // conversion function to the type we're eventually trying to
2837 // convert to (ToType), we need to synthesize a call to the
2838 // conversion function and attempt copy initialization from it. This
2839 // makes sure that we get the right semantics with respect to
2840 // lvalues/rvalues and the type. Fortunately, we can allocate this
2841 // call on the stack and we don't need its arguments to be
2842 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002843 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002844 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002845 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002846 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002847 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002848
2849 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002850 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2851 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002852 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002853 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002854 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002855 ImplicitConversionSequence ICS =
2856 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002857 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002858 /*ForceRValue=*/false,
2859 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002860
John McCall0d1da222010-01-12 00:44:57 +00002861 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002862 case ImplicitConversionSequence::StandardConversion:
2863 Candidate.FinalConversion = ICS.Standard;
2864 break;
2865
2866 case ImplicitConversionSequence::BadConversion:
2867 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002868 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002869 break;
2870
2871 default:
Mike Stump11289f42009-09-09 15:08:12 +00002872 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002873 "Can only end up with a standard conversion sequence or failure");
2874 }
2875}
2876
Douglas Gregor05155d82009-08-21 23:19:43 +00002877/// \brief Adds a conversion function template specialization
2878/// candidate to the overload set, using template argument deduction
2879/// to deduce the template arguments of the conversion function
2880/// template from the type that we are converting to (C++
2881/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002882void
Douglas Gregor05155d82009-08-21 23:19:43 +00002883Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002884 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002885 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002886 Expr *From, QualType ToType,
2887 OverloadCandidateSet &CandidateSet) {
2888 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2889 "Only conversion function templates permitted here");
2890
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002891 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2892 return;
2893
John McCallbc077cf2010-02-08 23:07:23 +00002894 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00002895 CXXConversionDecl *Specialization = 0;
2896 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002897 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002898 Specialization, Info)) {
2899 // FIXME: Record what happened with template argument deduction, so
2900 // that we can give the user a beautiful diagnostic.
2901 (void)Result;
2902 return;
2903 }
Mike Stump11289f42009-09-09 15:08:12 +00002904
Douglas Gregor05155d82009-08-21 23:19:43 +00002905 // Add the conversion function template specialization produced by
2906 // template argument deduction as a candidate.
2907 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002908 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2909 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002910}
2911
Douglas Gregorab7897a2008-11-19 22:57:39 +00002912/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2913/// converts the given @c Object to a function pointer via the
2914/// conversion function @c Conversion, and then attempts to call it
2915/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2916/// the type of function that we'll eventually be calling.
2917void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002918 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002919 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002920 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002921 QualType ObjectType,
2922 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002923 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002924 if (!CandidateSet.isNewCandidate(Conversion))
2925 return;
2926
Douglas Gregor27381f32009-11-23 12:27:39 +00002927 // Overload resolution is always an unevaluated context.
2928 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2929
Douglas Gregorab7897a2008-11-19 22:57:39 +00002930 CandidateSet.push_back(OverloadCandidate());
2931 OverloadCandidate& Candidate = CandidateSet.back();
2932 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00002933 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002934 Candidate.Surrogate = Conversion;
2935 Candidate.Viable = true;
2936 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002937 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002938 Candidate.Conversions.resize(NumArgs + 1);
2939
2940 // Determine the implicit conversion sequence for the implicit
2941 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002942 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002943 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002944 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002945 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002946 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00002947 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002948 return;
2949 }
2950
2951 // The first conversion is actually a user-defined conversion whose
2952 // first conversion is ObjectInit's standard conversion (which is
2953 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002954 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002955 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002956 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002957 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002958 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002959 = Candidate.Conversions[0].UserDefined.Before;
2960 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2961
Mike Stump11289f42009-09-09 15:08:12 +00002962 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002963 unsigned NumArgsInProto = Proto->getNumArgs();
2964
2965 // (C++ 13.3.2p2): A candidate function having fewer than m
2966 // parameters is viable only if it has an ellipsis in its parameter
2967 // list (8.3.5).
2968 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2969 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002970 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002971 return;
2972 }
2973
2974 // Function types don't have any default arguments, so just check if
2975 // we have enough arguments.
2976 if (NumArgs < NumArgsInProto) {
2977 // Not enough arguments.
2978 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002979 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002980 return;
2981 }
2982
2983 // Determine the implicit conversion sequences for each of the
2984 // arguments.
2985 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2986 if (ArgIdx < NumArgsInProto) {
2987 // (C++ 13.3.2p3): for F to be a viable function, there shall
2988 // exist for each argument an implicit conversion sequence
2989 // (13.3.3.1) that converts that argument to the corresponding
2990 // parameter of F.
2991 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002992 Candidate.Conversions[ArgIdx + 1]
2993 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002994 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002995 /*ForceRValue=*/false,
2996 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002997 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002998 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002999 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003000 break;
3001 }
3002 } else {
3003 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3004 // argument for which there is no corresponding parameter is
3005 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003006 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003007 }
3008 }
3009}
3010
Mike Stump87c57ac2009-05-16 07:39:55 +00003011// FIXME: This will eventually be removed, once we've migrated all of the
3012// operator overloading logic over to the scheme used by binary operators, which
3013// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003014void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003015 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003016 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003017 OverloadCandidateSet& CandidateSet,
3018 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003019 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003020
3021 QualType T1 = Args[0]->getType();
3022 QualType T2;
3023 if (NumArgs > 1)
3024 T2 = Args[1]->getType();
3025
3026 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003027 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003028 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3029 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3030 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3031 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003032 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003033 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003034}
3035
3036/// \brief Add overload candidates for overloaded operators that are
3037/// member functions.
3038///
3039/// Add the overloaded operator candidates that are member functions
3040/// for the operator Op that was used in an operator expression such
3041/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3042/// CandidateSet will store the added overload candidates. (C++
3043/// [over.match.oper]).
3044void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3045 SourceLocation OpLoc,
3046 Expr **Args, unsigned NumArgs,
3047 OverloadCandidateSet& CandidateSet,
3048 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003049 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3050
3051 // C++ [over.match.oper]p3:
3052 // For a unary operator @ with an operand of a type whose
3053 // cv-unqualified version is T1, and for a binary operator @ with
3054 // a left operand of a type whose cv-unqualified version is T1 and
3055 // a right operand of a type whose cv-unqualified version is T2,
3056 // three sets of candidate functions, designated member
3057 // candidates, non-member candidates and built-in candidates, are
3058 // constructed as follows:
3059 QualType T1 = Args[0]->getType();
3060 QualType T2;
3061 if (NumArgs > 1)
3062 T2 = Args[1]->getType();
3063
3064 // -- If T1 is a class type, the set of member candidates is the
3065 // result of the qualified lookup of T1::operator@
3066 // (13.3.1.1.1); otherwise, the set of member candidates is
3067 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003068 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003069 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003070 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003071 return;
Mike Stump11289f42009-09-09 15:08:12 +00003072
John McCall27b18f82009-11-17 02:14:36 +00003073 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3074 LookupQualifiedName(Operators, T1Rec->getDecl());
3075 Operators.suppressDiagnostics();
3076
Mike Stump11289f42009-09-09 15:08:12 +00003077 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003078 OperEnd = Operators.end();
3079 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003080 ++Oper)
John McCallb89836b2010-01-26 01:37:31 +00003081 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003082 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003083 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003084 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003085}
3086
Douglas Gregora11693b2008-11-12 17:17:38 +00003087/// AddBuiltinCandidate - Add a candidate for a built-in
3088/// operator. ResultTy and ParamTys are the result and parameter types
3089/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003090/// arguments being passed to the candidate. IsAssignmentOperator
3091/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003092/// operator. NumContextualBoolArguments is the number of arguments
3093/// (at the beginning of the argument list) that will be contextually
3094/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003095void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003096 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003097 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003098 bool IsAssignmentOperator,
3099 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003100 // Overload resolution is always an unevaluated context.
3101 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3102
Douglas Gregora11693b2008-11-12 17:17:38 +00003103 // Add this candidate
3104 CandidateSet.push_back(OverloadCandidate());
3105 OverloadCandidate& Candidate = CandidateSet.back();
3106 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00003107 Candidate.Access = AS_none;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003108 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003109 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003110 Candidate.BuiltinTypes.ResultTy = ResultTy;
3111 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3112 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3113
3114 // Determine the implicit conversion sequences for each of the
3115 // arguments.
3116 Candidate.Viable = true;
3117 Candidate.Conversions.resize(NumArgs);
3118 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003119 // C++ [over.match.oper]p4:
3120 // For the built-in assignment operators, conversions of the
3121 // left operand are restricted as follows:
3122 // -- no temporaries are introduced to hold the left operand, and
3123 // -- no user-defined conversions are applied to the left
3124 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003125 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003126 //
3127 // We block these conversions by turning off user-defined
3128 // conversions, since that is the only way that initialization of
3129 // a reference to a non-class type can occur from something that
3130 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003131 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003132 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003133 "Contextual conversion to bool requires bool type");
3134 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3135 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003136 Candidate.Conversions[ArgIdx]
3137 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003138 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003139 /*ForceRValue=*/false,
3140 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003141 }
John McCall0d1da222010-01-12 00:44:57 +00003142 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003143 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003144 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003145 break;
3146 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003147 }
3148}
3149
3150/// BuiltinCandidateTypeSet - A set of types that will be used for the
3151/// candidate operator functions for built-in operators (C++
3152/// [over.built]). The types are separated into pointer types and
3153/// enumeration types.
3154class BuiltinCandidateTypeSet {
3155 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003156 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003157
3158 /// PointerTypes - The set of pointer types that will be used in the
3159 /// built-in candidates.
3160 TypeSet PointerTypes;
3161
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003162 /// MemberPointerTypes - The set of member pointer types that will be
3163 /// used in the built-in candidates.
3164 TypeSet MemberPointerTypes;
3165
Douglas Gregora11693b2008-11-12 17:17:38 +00003166 /// EnumerationTypes - The set of enumeration types that will be
3167 /// used in the built-in candidates.
3168 TypeSet EnumerationTypes;
3169
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003170 /// Sema - The semantic analysis instance where we are building the
3171 /// candidate type set.
3172 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003173
Douglas Gregora11693b2008-11-12 17:17:38 +00003174 /// Context - The AST context in which we will build the type sets.
3175 ASTContext &Context;
3176
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003177 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3178 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003179 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003180
3181public:
3182 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003183 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003184
Mike Stump11289f42009-09-09 15:08:12 +00003185 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003186 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003187
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003188 void AddTypesConvertedFrom(QualType Ty,
3189 SourceLocation Loc,
3190 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003191 bool AllowExplicitConversions,
3192 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003193
3194 /// pointer_begin - First pointer type found;
3195 iterator pointer_begin() { return PointerTypes.begin(); }
3196
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003197 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003198 iterator pointer_end() { return PointerTypes.end(); }
3199
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003200 /// member_pointer_begin - First member pointer type found;
3201 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3202
3203 /// member_pointer_end - Past the last member pointer type found;
3204 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3205
Douglas Gregora11693b2008-11-12 17:17:38 +00003206 /// enumeration_begin - First enumeration type found;
3207 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3208
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003209 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003210 iterator enumeration_end() { return EnumerationTypes.end(); }
3211};
3212
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003213/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003214/// the set of pointer types along with any more-qualified variants of
3215/// that type. For example, if @p Ty is "int const *", this routine
3216/// will add "int const *", "int const volatile *", "int const
3217/// restrict *", and "int const volatile restrict *" to the set of
3218/// pointer types. Returns true if the add of @p Ty itself succeeded,
3219/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003220///
3221/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003222bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003223BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3224 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003225
Douglas Gregora11693b2008-11-12 17:17:38 +00003226 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003227 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003228 return false;
3229
John McCall8ccfcb52009-09-24 19:53:00 +00003230 const PointerType *PointerTy = Ty->getAs<PointerType>();
3231 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003232
John McCall8ccfcb52009-09-24 19:53:00 +00003233 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003234 // Don't add qualified variants of arrays. For one, they're not allowed
3235 // (the qualifier would sink to the element type), and for another, the
3236 // only overload situation where it matters is subscript or pointer +- int,
3237 // and those shouldn't have qualifier variants anyway.
3238 if (PointeeTy->isArrayType())
3239 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003240 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003241 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003242 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003243 bool hasVolatile = VisibleQuals.hasVolatile();
3244 bool hasRestrict = VisibleQuals.hasRestrict();
3245
John McCall8ccfcb52009-09-24 19:53:00 +00003246 // Iterate through all strict supersets of BaseCVR.
3247 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3248 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003249 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3250 // in the types.
3251 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3252 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003253 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3254 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003255 }
3256
3257 return true;
3258}
3259
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003260/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3261/// to the set of pointer types along with any more-qualified variants of
3262/// that type. For example, if @p Ty is "int const *", this routine
3263/// will add "int const *", "int const volatile *", "int const
3264/// restrict *", and "int const volatile restrict *" to the set of
3265/// pointer types. Returns true if the add of @p Ty itself succeeded,
3266/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003267///
3268/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003269bool
3270BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3271 QualType Ty) {
3272 // Insert this type.
3273 if (!MemberPointerTypes.insert(Ty))
3274 return false;
3275
John McCall8ccfcb52009-09-24 19:53:00 +00003276 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3277 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003278
John McCall8ccfcb52009-09-24 19:53:00 +00003279 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003280 // Don't add qualified variants of arrays. For one, they're not allowed
3281 // (the qualifier would sink to the element type), and for another, the
3282 // only overload situation where it matters is subscript or pointer +- int,
3283 // and those shouldn't have qualifier variants anyway.
3284 if (PointeeTy->isArrayType())
3285 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003286 const Type *ClassTy = PointerTy->getClass();
3287
3288 // Iterate through all strict supersets of the pointee type's CVR
3289 // qualifiers.
3290 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3291 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3292 if ((CVR | BaseCVR) != CVR) continue;
3293
3294 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3295 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003296 }
3297
3298 return true;
3299}
3300
Douglas Gregora11693b2008-11-12 17:17:38 +00003301/// AddTypesConvertedFrom - Add each of the types to which the type @p
3302/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003303/// primarily interested in pointer types and enumeration types. We also
3304/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003305/// AllowUserConversions is true if we should look at the conversion
3306/// functions of a class type, and AllowExplicitConversions if we
3307/// should also include the explicit conversion functions of a class
3308/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003309void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003310BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003311 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003312 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003313 bool AllowExplicitConversions,
3314 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003315 // Only deal with canonical types.
3316 Ty = Context.getCanonicalType(Ty);
3317
3318 // Look through reference types; they aren't part of the type of an
3319 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003320 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003321 Ty = RefTy->getPointeeType();
3322
3323 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003324 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003325
Sebastian Redl65ae2002009-11-05 16:36:20 +00003326 // If we're dealing with an array type, decay to the pointer.
3327 if (Ty->isArrayType())
3328 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3329
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003330 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003331 QualType PointeeTy = PointerTy->getPointeeType();
3332
3333 // Insert our type, and its more-qualified variants, into the set
3334 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003335 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003336 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003337 } else if (Ty->isMemberPointerType()) {
3338 // Member pointers are far easier, since the pointee can't be converted.
3339 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3340 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003341 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003342 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003343 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003344 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003345 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003346 // No conversion functions in incomplete types.
3347 return;
3348 }
Mike Stump11289f42009-09-09 15:08:12 +00003349
Douglas Gregora11693b2008-11-12 17:17:38 +00003350 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003351 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003352 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003353 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003354 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003355
Mike Stump11289f42009-09-09 15:08:12 +00003356 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003357 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003358 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003359 continue;
3360
John McCalld14a8642009-11-21 08:51:07 +00003361 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003362 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003363 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003364 VisibleQuals);
3365 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003366 }
3367 }
3368 }
3369}
3370
Douglas Gregor84605ae2009-08-24 13:43:27 +00003371/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3372/// the volatile- and non-volatile-qualified assignment operators for the
3373/// given type to the candidate set.
3374static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3375 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003376 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003377 unsigned NumArgs,
3378 OverloadCandidateSet &CandidateSet) {
3379 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003380
Douglas Gregor84605ae2009-08-24 13:43:27 +00003381 // T& operator=(T&, T)
3382 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3383 ParamTypes[1] = T;
3384 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3385 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003386
Douglas Gregor84605ae2009-08-24 13:43:27 +00003387 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3388 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003389 ParamTypes[0]
3390 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003391 ParamTypes[1] = T;
3392 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003393 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003394 }
3395}
Mike Stump11289f42009-09-09 15:08:12 +00003396
Sebastian Redl1054fae2009-10-25 17:03:50 +00003397/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3398/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003399static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3400 Qualifiers VRQuals;
3401 const RecordType *TyRec;
3402 if (const MemberPointerType *RHSMPType =
3403 ArgExpr->getType()->getAs<MemberPointerType>())
3404 TyRec = cast<RecordType>(RHSMPType->getClass());
3405 else
3406 TyRec = ArgExpr->getType()->getAs<RecordType>();
3407 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003408 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003409 VRQuals.addVolatile();
3410 VRQuals.addRestrict();
3411 return VRQuals;
3412 }
3413
3414 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003415 if (!ClassDecl->hasDefinition())
3416 return VRQuals;
3417
John McCallad371252010-01-20 00:46:10 +00003418 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003419 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003420
John McCallad371252010-01-20 00:46:10 +00003421 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003422 E = Conversions->end(); I != E; ++I) {
3423 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003424 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3425 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3426 CanTy = ResTypeRef->getPointeeType();
3427 // Need to go down the pointer/mempointer chain and add qualifiers
3428 // as see them.
3429 bool done = false;
3430 while (!done) {
3431 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3432 CanTy = ResTypePtr->getPointeeType();
3433 else if (const MemberPointerType *ResTypeMPtr =
3434 CanTy->getAs<MemberPointerType>())
3435 CanTy = ResTypeMPtr->getPointeeType();
3436 else
3437 done = true;
3438 if (CanTy.isVolatileQualified())
3439 VRQuals.addVolatile();
3440 if (CanTy.isRestrictQualified())
3441 VRQuals.addRestrict();
3442 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3443 return VRQuals;
3444 }
3445 }
3446 }
3447 return VRQuals;
3448}
3449
Douglas Gregord08452f2008-11-19 15:42:04 +00003450/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3451/// operator overloads to the candidate set (C++ [over.built]), based
3452/// on the operator @p Op and the arguments given. For example, if the
3453/// operator is a binary '+', this routine might add "int
3454/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003455void
Mike Stump11289f42009-09-09 15:08:12 +00003456Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003457 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003458 Expr **Args, unsigned NumArgs,
3459 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003460 // The set of "promoted arithmetic types", which are the arithmetic
3461 // types are that preserved by promotion (C++ [over.built]p2). Note
3462 // that the first few of these types are the promoted integral
3463 // types; these types need to be first.
3464 // FIXME: What about complex?
3465 const unsigned FirstIntegralType = 0;
3466 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003467 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003468 LastPromotedIntegralType = 13;
3469 const unsigned FirstPromotedArithmeticType = 7,
3470 LastPromotedArithmeticType = 16;
3471 const unsigned NumArithmeticTypes = 16;
3472 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003473 Context.BoolTy, Context.CharTy, Context.WCharTy,
3474// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003475 Context.SignedCharTy, Context.ShortTy,
3476 Context.UnsignedCharTy, Context.UnsignedShortTy,
3477 Context.IntTy, Context.LongTy, Context.LongLongTy,
3478 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3479 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3480 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003481 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3482 "Invalid first promoted integral type");
3483 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3484 == Context.UnsignedLongLongTy &&
3485 "Invalid last promoted integral type");
3486 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3487 "Invalid first promoted arithmetic type");
3488 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3489 == Context.LongDoubleTy &&
3490 "Invalid last promoted arithmetic type");
3491
Douglas Gregora11693b2008-11-12 17:17:38 +00003492 // Find all of the types that the arguments can convert to, but only
3493 // if the operator we're looking at has built-in operator candidates
3494 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003495 Qualifiers VisibleTypeConversionsQuals;
3496 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003497 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3498 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3499
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003500 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003501 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3502 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003503 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003504 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003505 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003506 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003507 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003508 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003509 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003510 true,
3511 (Op == OO_Exclaim ||
3512 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003513 Op == OO_PipePipe),
3514 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003515 }
3516
3517 bool isComparison = false;
3518 switch (Op) {
3519 case OO_None:
3520 case NUM_OVERLOADED_OPERATORS:
3521 assert(false && "Expected an overloaded operator");
3522 break;
3523
Douglas Gregord08452f2008-11-19 15:42:04 +00003524 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003525 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003526 goto UnaryStar;
3527 else
3528 goto BinaryStar;
3529 break;
3530
3531 case OO_Plus: // '+' is either unary or binary
3532 if (NumArgs == 1)
3533 goto UnaryPlus;
3534 else
3535 goto BinaryPlus;
3536 break;
3537
3538 case OO_Minus: // '-' is either unary or binary
3539 if (NumArgs == 1)
3540 goto UnaryMinus;
3541 else
3542 goto BinaryMinus;
3543 break;
3544
3545 case OO_Amp: // '&' is either unary or binary
3546 if (NumArgs == 1)
3547 goto UnaryAmp;
3548 else
3549 goto BinaryAmp;
3550
3551 case OO_PlusPlus:
3552 case OO_MinusMinus:
3553 // C++ [over.built]p3:
3554 //
3555 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3556 // is either volatile or empty, there exist candidate operator
3557 // functions of the form
3558 //
3559 // VQ T& operator++(VQ T&);
3560 // T operator++(VQ T&, int);
3561 //
3562 // C++ [over.built]p4:
3563 //
3564 // For every pair (T, VQ), where T is an arithmetic type other
3565 // than bool, and VQ is either volatile or empty, there exist
3566 // candidate operator functions of the form
3567 //
3568 // VQ T& operator--(VQ T&);
3569 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003570 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003571 Arith < NumArithmeticTypes; ++Arith) {
3572 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003573 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003574 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003575
3576 // Non-volatile version.
3577 if (NumArgs == 1)
3578 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3579 else
3580 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003581 // heuristic to reduce number of builtin candidates in the set.
3582 // Add volatile version only if there are conversions to a volatile type.
3583 if (VisibleTypeConversionsQuals.hasVolatile()) {
3584 // Volatile version
3585 ParamTypes[0]
3586 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3587 if (NumArgs == 1)
3588 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3589 else
3590 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3591 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003592 }
3593
3594 // C++ [over.built]p5:
3595 //
3596 // For every pair (T, VQ), where T is a cv-qualified or
3597 // cv-unqualified object type, and VQ is either volatile or
3598 // empty, there exist candidate operator functions of the form
3599 //
3600 // T*VQ& operator++(T*VQ&);
3601 // T*VQ& operator--(T*VQ&);
3602 // T* operator++(T*VQ&, int);
3603 // T* operator--(T*VQ&, int);
3604 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3605 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3606 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003607 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003608 continue;
3609
Mike Stump11289f42009-09-09 15:08:12 +00003610 QualType ParamTypes[2] = {
3611 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003612 };
Mike Stump11289f42009-09-09 15:08:12 +00003613
Douglas Gregord08452f2008-11-19 15:42:04 +00003614 // Without volatile
3615 if (NumArgs == 1)
3616 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3617 else
3618 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3619
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003620 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3621 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003622 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003623 ParamTypes[0]
3624 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003625 if (NumArgs == 1)
3626 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3627 else
3628 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3629 }
3630 }
3631 break;
3632
3633 UnaryStar:
3634 // C++ [over.built]p6:
3635 // For every cv-qualified or cv-unqualified object type T, there
3636 // exist candidate operator functions of the form
3637 //
3638 // T& operator*(T*);
3639 //
3640 // C++ [over.built]p7:
3641 // For every function type T, there exist candidate operator
3642 // functions of the form
3643 // T& operator*(T*);
3644 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3645 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3646 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003647 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003648 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003649 &ParamTy, Args, 1, CandidateSet);
3650 }
3651 break;
3652
3653 UnaryPlus:
3654 // C++ [over.built]p8:
3655 // For every type T, there exist candidate operator functions of
3656 // the form
3657 //
3658 // T* operator+(T*);
3659 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3660 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3661 QualType ParamTy = *Ptr;
3662 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3663 }
Mike Stump11289f42009-09-09 15:08:12 +00003664
Douglas Gregord08452f2008-11-19 15:42:04 +00003665 // Fall through
3666
3667 UnaryMinus:
3668 // C++ [over.built]p9:
3669 // For every promoted arithmetic type T, there exist candidate
3670 // operator functions of the form
3671 //
3672 // T operator+(T);
3673 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003674 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003675 Arith < LastPromotedArithmeticType; ++Arith) {
3676 QualType ArithTy = ArithmeticTypes[Arith];
3677 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3678 }
3679 break;
3680
3681 case OO_Tilde:
3682 // C++ [over.built]p10:
3683 // For every promoted integral type T, there exist candidate
3684 // operator functions of the form
3685 //
3686 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003687 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003688 Int < LastPromotedIntegralType; ++Int) {
3689 QualType IntTy = ArithmeticTypes[Int];
3690 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3691 }
3692 break;
3693
Douglas Gregora11693b2008-11-12 17:17:38 +00003694 case OO_New:
3695 case OO_Delete:
3696 case OO_Array_New:
3697 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003698 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003699 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003700 break;
3701
3702 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003703 UnaryAmp:
3704 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003705 // C++ [over.match.oper]p3:
3706 // -- For the operator ',', the unary operator '&', or the
3707 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003708 break;
3709
Douglas Gregor84605ae2009-08-24 13:43:27 +00003710 case OO_EqualEqual:
3711 case OO_ExclaimEqual:
3712 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003713 // For every pointer to member type T, there exist candidate operator
3714 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003715 //
3716 // bool operator==(T,T);
3717 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003718 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003719 MemPtr = CandidateTypes.member_pointer_begin(),
3720 MemPtrEnd = CandidateTypes.member_pointer_end();
3721 MemPtr != MemPtrEnd;
3722 ++MemPtr) {
3723 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3724 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3725 }
Mike Stump11289f42009-09-09 15:08:12 +00003726
Douglas Gregor84605ae2009-08-24 13:43:27 +00003727 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003728
Douglas Gregora11693b2008-11-12 17:17:38 +00003729 case OO_Less:
3730 case OO_Greater:
3731 case OO_LessEqual:
3732 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003733 // C++ [over.built]p15:
3734 //
3735 // For every pointer or enumeration type T, there exist
3736 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003737 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003738 // bool operator<(T, T);
3739 // 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 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3745 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3746 QualType ParamTypes[2] = { *Ptr, *Ptr };
3747 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3748 }
Mike Stump11289f42009-09-09 15:08:12 +00003749 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003750 = CandidateTypes.enumeration_begin();
3751 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3752 QualType ParamTypes[2] = { *Enum, *Enum };
3753 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3754 }
3755
3756 // Fall through.
3757 isComparison = true;
3758
Douglas Gregord08452f2008-11-19 15:42:04 +00003759 BinaryPlus:
3760 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003761 if (!isComparison) {
3762 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3763
3764 // C++ [over.built]p13:
3765 //
3766 // For every cv-qualified or cv-unqualified object type T
3767 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003768 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003769 // T* operator+(T*, ptrdiff_t);
3770 // T& operator[](T*, ptrdiff_t); [BELOW]
3771 // T* operator-(T*, ptrdiff_t);
3772 // T* operator+(ptrdiff_t, T*);
3773 // T& operator[](ptrdiff_t, T*); [BELOW]
3774 //
3775 // C++ [over.built]p14:
3776 //
3777 // For every T, where T is a pointer to object type, there
3778 // exist candidate operator functions of the form
3779 //
3780 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003781 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003782 = CandidateTypes.pointer_begin();
3783 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3784 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3785
3786 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3787 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3788
3789 if (Op == OO_Plus) {
3790 // T* operator+(ptrdiff_t, T*);
3791 ParamTypes[0] = ParamTypes[1];
3792 ParamTypes[1] = *Ptr;
3793 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3794 } else {
3795 // ptrdiff_t operator-(T, T);
3796 ParamTypes[1] = *Ptr;
3797 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3798 Args, 2, CandidateSet);
3799 }
3800 }
3801 }
3802 // Fall through
3803
Douglas Gregora11693b2008-11-12 17:17:38 +00003804 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003805 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003806 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003807 // C++ [over.built]p12:
3808 //
3809 // For every pair of promoted arithmetic types L and R, there
3810 // exist candidate operator functions of the form
3811 //
3812 // LR operator*(L, R);
3813 // LR operator/(L, R);
3814 // LR operator+(L, R);
3815 // LR operator-(L, R);
3816 // bool 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 //
3823 // where LR is the result of the usual arithmetic conversions
3824 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003825 //
3826 // C++ [over.built]p24:
3827 //
3828 // For every pair of promoted arithmetic types L and R, there exist
3829 // candidate operator functions of the form
3830 //
3831 // LR operator?(bool, L, R);
3832 //
3833 // where LR is the result of the usual arithmetic conversions
3834 // between types L and R.
3835 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003836 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003837 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003838 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003839 Right < LastPromotedArithmeticType; ++Right) {
3840 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003841 QualType Result
3842 = isComparison
3843 ? Context.BoolTy
3844 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003845 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3846 }
3847 }
3848 break;
3849
3850 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003851 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003852 case OO_Caret:
3853 case OO_Pipe:
3854 case OO_LessLess:
3855 case OO_GreaterGreater:
3856 // C++ [over.built]p17:
3857 //
3858 // For every pair of promoted integral types L and R, there
3859 // exist candidate operator functions of the form
3860 //
3861 // LR operator%(L, R);
3862 // LR operator&(L, R);
3863 // LR operator^(L, R);
3864 // LR operator|(L, R);
3865 // L operator<<(L, R);
3866 // L operator>>(L, R);
3867 //
3868 // where LR is the result of the usual arithmetic conversions
3869 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003870 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003871 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003872 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003873 Right < LastPromotedIntegralType; ++Right) {
3874 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3875 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3876 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003877 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003878 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3879 }
3880 }
3881 break;
3882
3883 case OO_Equal:
3884 // C++ [over.built]p20:
3885 //
3886 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003887 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003888 // empty, there exist candidate operator functions of the form
3889 //
3890 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003891 for (BuiltinCandidateTypeSet::iterator
3892 Enum = CandidateTypes.enumeration_begin(),
3893 EnumEnd = CandidateTypes.enumeration_end();
3894 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003895 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003896 CandidateSet);
3897 for (BuiltinCandidateTypeSet::iterator
3898 MemPtr = CandidateTypes.member_pointer_begin(),
3899 MemPtrEnd = CandidateTypes.member_pointer_end();
3900 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003901 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003902 CandidateSet);
3903 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003904
3905 case OO_PlusEqual:
3906 case OO_MinusEqual:
3907 // C++ [over.built]p19:
3908 //
3909 // For every pair (T, VQ), where T is any type and VQ is either
3910 // volatile or empty, there exist candidate operator functions
3911 // of the form
3912 //
3913 // T*VQ& operator=(T*VQ&, T*);
3914 //
3915 // C++ [over.built]p21:
3916 //
3917 // For every pair (T, VQ), where T is a cv-qualified or
3918 // cv-unqualified object type and VQ is either volatile or
3919 // empty, there exist candidate operator functions of the form
3920 //
3921 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3922 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3923 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3924 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3925 QualType ParamTypes[2];
3926 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3927
3928 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003929 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003930 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3931 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003932
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003933 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3934 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003935 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003936 ParamTypes[0]
3937 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003938 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3939 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003940 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003941 }
3942 // Fall through.
3943
3944 case OO_StarEqual:
3945 case OO_SlashEqual:
3946 // C++ [over.built]p18:
3947 //
3948 // For every triple (L, VQ, R), where L is an arithmetic type,
3949 // VQ is either volatile or empty, and R is a promoted
3950 // arithmetic type, there exist candidate operator functions of
3951 // the form
3952 //
3953 // VQ L& operator=(VQ L&, R);
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 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003959 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003960 Right < LastPromotedArithmeticType; ++Right) {
3961 QualType ParamTypes[2];
3962 ParamTypes[1] = ArithmeticTypes[Right];
3963
3964 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003965 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003966 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3967 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003968
3969 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003970 if (VisibleTypeConversionsQuals.hasVolatile()) {
3971 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3972 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3973 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3974 /*IsAssigmentOperator=*/Op == OO_Equal);
3975 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003976 }
3977 }
3978 break;
3979
3980 case OO_PercentEqual:
3981 case OO_LessLessEqual:
3982 case OO_GreaterGreaterEqual:
3983 case OO_AmpEqual:
3984 case OO_CaretEqual:
3985 case OO_PipeEqual:
3986 // C++ [over.built]p22:
3987 //
3988 // For every triple (L, VQ, R), where L is an integral type, VQ
3989 // is either volatile or empty, and R is a promoted integral
3990 // type, there exist candidate operator functions of the form
3991 //
3992 // VQ L& operator%=(VQ L&, R);
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 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003999 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004000 Right < LastPromotedIntegralType; ++Right) {
4001 QualType ParamTypes[2];
4002 ParamTypes[1] = ArithmeticTypes[Right];
4003
4004 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004005 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004006 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004007 if (VisibleTypeConversionsQuals.hasVolatile()) {
4008 // Add this built-in operator as a candidate (VQ is 'volatile').
4009 ParamTypes[0] = ArithmeticTypes[Left];
4010 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4011 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4012 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4013 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004014 }
4015 }
4016 break;
4017
Douglas Gregord08452f2008-11-19 15:42:04 +00004018 case OO_Exclaim: {
4019 // C++ [over.operator]p23:
4020 //
4021 // There also exist candidate operator functions of the form
4022 //
Mike Stump11289f42009-09-09 15:08:12 +00004023 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004024 // bool operator&&(bool, bool); [BELOW]
4025 // bool operator||(bool, bool); [BELOW]
4026 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004027 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4028 /*IsAssignmentOperator=*/false,
4029 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004030 break;
4031 }
4032
Douglas Gregora11693b2008-11-12 17:17:38 +00004033 case OO_AmpAmp:
4034 case OO_PipePipe: {
4035 // C++ [over.operator]p23:
4036 //
4037 // There also exist candidate operator functions of the form
4038 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004039 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004040 // bool operator&&(bool, bool);
4041 // bool operator||(bool, bool);
4042 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004043 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4044 /*IsAssignmentOperator=*/false,
4045 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004046 break;
4047 }
4048
4049 case OO_Subscript:
4050 // C++ [over.built]p13:
4051 //
4052 // For every cv-qualified or cv-unqualified object type T there
4053 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004054 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004055 // T* operator+(T*, ptrdiff_t); [ABOVE]
4056 // T& operator[](T*, ptrdiff_t);
4057 // T* operator-(T*, ptrdiff_t); [ABOVE]
4058 // T* operator+(ptrdiff_t, T*); [ABOVE]
4059 // T& operator[](ptrdiff_t, T*);
4060 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4061 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4062 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004063 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004064 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004065
4066 // T& operator[](T*, ptrdiff_t)
4067 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4068
4069 // T& operator[](ptrdiff_t, T*);
4070 ParamTypes[0] = ParamTypes[1];
4071 ParamTypes[1] = *Ptr;
4072 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4073 }
4074 break;
4075
4076 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004077 // C++ [over.built]p11:
4078 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4079 // C1 is the same type as C2 or is a derived class of C2, T is an object
4080 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4081 // there exist candidate operator functions of the form
4082 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4083 // where CV12 is the union of CV1 and CV2.
4084 {
4085 for (BuiltinCandidateTypeSet::iterator Ptr =
4086 CandidateTypes.pointer_begin();
4087 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4088 QualType C1Ty = (*Ptr);
4089 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004090 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004091 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004092 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004093 if (!isa<RecordType>(C1))
4094 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004095 // heuristic to reduce number of builtin candidates in the set.
4096 // Add volatile/restrict version only if there are conversions to a
4097 // volatile/restrict type.
4098 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4099 continue;
4100 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4101 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004102 }
4103 for (BuiltinCandidateTypeSet::iterator
4104 MemPtr = CandidateTypes.member_pointer_begin(),
4105 MemPtrEnd = CandidateTypes.member_pointer_end();
4106 MemPtr != MemPtrEnd; ++MemPtr) {
4107 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4108 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004109 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004110 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4111 break;
4112 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4113 // build CV12 T&
4114 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004115 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4116 T.isVolatileQualified())
4117 continue;
4118 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4119 T.isRestrictQualified())
4120 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004121 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004122 QualType ResultTy = Context.getLValueReferenceType(T);
4123 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4124 }
4125 }
4126 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004127 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004128
4129 case OO_Conditional:
4130 // Note that we don't consider the first argument, since it has been
4131 // contextually converted to bool long ago. The candidates below are
4132 // therefore added as binary.
4133 //
4134 // C++ [over.built]p24:
4135 // For every type T, where T is a pointer or pointer-to-member type,
4136 // there exist candidate operator functions of the form
4137 //
4138 // T operator?(bool, T, T);
4139 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004140 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4141 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4142 QualType ParamTypes[2] = { *Ptr, *Ptr };
4143 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4144 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004145 for (BuiltinCandidateTypeSet::iterator Ptr =
4146 CandidateTypes.member_pointer_begin(),
4147 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4148 QualType ParamTypes[2] = { *Ptr, *Ptr };
4149 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4150 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004151 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004152 }
4153}
4154
Douglas Gregore254f902009-02-04 00:32:51 +00004155/// \brief Add function candidates found via argument-dependent lookup
4156/// to the set of overloading candidates.
4157///
4158/// This routine performs argument-dependent name lookup based on the
4159/// given function name (which may also be an operator name) and adds
4160/// all of the overload candidates found by ADL to the overload
4161/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004162void
Douglas Gregore254f902009-02-04 00:32:51 +00004163Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004164 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004165 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004166 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004167 OverloadCandidateSet& CandidateSet,
4168 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004169 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004170
John McCall91f61fc2010-01-26 06:04:06 +00004171 // FIXME: This approach for uniquing ADL results (and removing
4172 // redundant candidates from the set) relies on pointer-equality,
4173 // which means we need to key off the canonical decl. However,
4174 // always going back to the canonical decl might not get us the
4175 // right set of default arguments. What default arguments are
4176 // we supposed to consider on ADL candidates, anyway?
4177
Douglas Gregorcabea402009-09-22 15:41:20 +00004178 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004179 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004180
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004181 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004182 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4183 CandEnd = CandidateSet.end();
4184 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004185 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004186 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004187 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004188 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004189 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004190
4191 // For each of the ADL candidates we found, add it to the overload
4192 // set.
John McCall8fe68082010-01-26 07:16:45 +00004193 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00004194 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004195 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004196 continue;
4197
John McCallb89836b2010-01-26 01:37:31 +00004198 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004199 false, false, PartialOverloading);
4200 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004201 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCallb89836b2010-01-26 01:37:31 +00004202 AS_none, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004203 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004204 }
Douglas Gregore254f902009-02-04 00:32:51 +00004205}
4206
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004207/// isBetterOverloadCandidate - Determines whether the first overload
4208/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004209bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004210Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004211 const OverloadCandidate& Cand2,
4212 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004213 // Define viable functions to be better candidates than non-viable
4214 // functions.
4215 if (!Cand2.Viable)
4216 return Cand1.Viable;
4217 else if (!Cand1.Viable)
4218 return false;
4219
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004220 // C++ [over.match.best]p1:
4221 //
4222 // -- if F is a static member function, ICS1(F) is defined such
4223 // that ICS1(F) is neither better nor worse than ICS1(G) for
4224 // any function G, and, symmetrically, ICS1(G) is neither
4225 // better nor worse than ICS1(F).
4226 unsigned StartArg = 0;
4227 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4228 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004229
Douglas Gregord3cb3562009-07-07 23:38:56 +00004230 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004231 // A viable function F1 is defined to be a better function than another
4232 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004233 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004234 unsigned NumArgs = Cand1.Conversions.size();
4235 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4236 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004237 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004238 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4239 Cand2.Conversions[ArgIdx])) {
4240 case ImplicitConversionSequence::Better:
4241 // Cand1 has a better conversion sequence.
4242 HasBetterConversion = true;
4243 break;
4244
4245 case ImplicitConversionSequence::Worse:
4246 // Cand1 can't be better than Cand2.
4247 return false;
4248
4249 case ImplicitConversionSequence::Indistinguishable:
4250 // Do nothing.
4251 break;
4252 }
4253 }
4254
Mike Stump11289f42009-09-09 15:08:12 +00004255 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004256 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004257 if (HasBetterConversion)
4258 return true;
4259
Mike Stump11289f42009-09-09 15:08:12 +00004260 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004261 // specialization, or, if not that,
4262 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4263 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4264 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004265
4266 // -- F1 and F2 are function template specializations, and the function
4267 // template for F1 is more specialized than the template for F2
4268 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004269 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004270 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4271 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004272 if (FunctionTemplateDecl *BetterTemplate
4273 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4274 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004275 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004276 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4277 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004278 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004279
Douglas Gregora1f013e2008-11-07 22:36:19 +00004280 // -- the context is an initialization by user-defined conversion
4281 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4282 // from the return type of F1 to the destination type (i.e.,
4283 // the type of the entity being initialized) is a better
4284 // conversion sequence than the standard conversion sequence
4285 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004286 if (Cand1.Function && Cand2.Function &&
4287 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004288 isa<CXXConversionDecl>(Cand2.Function)) {
4289 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4290 Cand2.FinalConversion)) {
4291 case ImplicitConversionSequence::Better:
4292 // Cand1 has a better conversion sequence.
4293 return true;
4294
4295 case ImplicitConversionSequence::Worse:
4296 // Cand1 can't be better than Cand2.
4297 return false;
4298
4299 case ImplicitConversionSequence::Indistinguishable:
4300 // Do nothing
4301 break;
4302 }
4303 }
4304
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004305 return false;
4306}
4307
Mike Stump11289f42009-09-09 15:08:12 +00004308/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004309/// within an overload candidate set.
4310///
4311/// \param CandidateSet the set of candidate functions.
4312///
4313/// \param Loc the location of the function name (or operator symbol) for
4314/// which overload resolution occurs.
4315///
Mike Stump11289f42009-09-09 15:08:12 +00004316/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004317/// function, Best points to the candidate function found.
4318///
4319/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004320OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4321 SourceLocation Loc,
4322 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004323 // Find the best viable function.
4324 Best = CandidateSet.end();
4325 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4326 Cand != CandidateSet.end(); ++Cand) {
4327 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004328 if (Best == CandidateSet.end() ||
4329 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004330 Best = Cand;
4331 }
4332 }
4333
4334 // If we didn't find any viable functions, abort.
4335 if (Best == CandidateSet.end())
4336 return OR_No_Viable_Function;
4337
4338 // Make sure that this function is better than every other viable
4339 // function. If not, we have an ambiguity.
4340 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4341 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004342 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004343 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004344 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004345 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004346 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004347 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004348 }
Mike Stump11289f42009-09-09 15:08:12 +00004349
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004350 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004351 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004352 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004353 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004354 return OR_Deleted;
4355
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004356 // C++ [basic.def.odr]p2:
4357 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004358 // when referred to from a potentially-evaluated expression. [Note: this
4359 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004360 // (clause 13), user-defined conversions (12.3.2), allocation function for
4361 // placement new (5.3.4), as well as non-default initialization (8.5).
4362 if (Best->Function)
4363 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004364 return OR_Success;
4365}
4366
John McCall53262c92010-01-12 02:15:36 +00004367namespace {
4368
4369enum OverloadCandidateKind {
4370 oc_function,
4371 oc_method,
4372 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004373 oc_function_template,
4374 oc_method_template,
4375 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004376 oc_implicit_default_constructor,
4377 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004378 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004379};
4380
John McCalle1ac8d12010-01-13 00:25:19 +00004381OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4382 FunctionDecl *Fn,
4383 std::string &Description) {
4384 bool isTemplate = false;
4385
4386 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4387 isTemplate = true;
4388 Description = S.getTemplateArgumentBindingsText(
4389 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4390 }
John McCallfd0b2f82010-01-06 09:43:14 +00004391
4392 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004393 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004394 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004395
John McCall53262c92010-01-12 02:15:36 +00004396 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4397 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004398 }
4399
4400 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4401 // This actually gets spelled 'candidate function' for now, but
4402 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004403 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004404 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004405
4406 assert(Meth->isCopyAssignment()
4407 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004408 return oc_implicit_copy_assignment;
4409 }
4410
John McCalle1ac8d12010-01-13 00:25:19 +00004411 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004412}
4413
4414} // end anonymous namespace
4415
4416// Notes the location of an overload candidate.
4417void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004418 std::string FnDesc;
4419 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4420 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4421 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004422}
4423
John McCall0d1da222010-01-12 00:44:57 +00004424/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4425/// "lead" diagnostic; it will be given two arguments, the source and
4426/// target types of the conversion.
4427void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4428 SourceLocation CaretLoc,
4429 const PartialDiagnostic &PDiag) {
4430 Diag(CaretLoc, PDiag)
4431 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4432 for (AmbiguousConversionSequence::const_iterator
4433 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4434 NoteOverloadCandidate(*I);
4435 }
John McCall12f97bc2010-01-08 04:41:39 +00004436}
4437
John McCall0d1da222010-01-12 00:44:57 +00004438namespace {
4439
John McCall6a61b522010-01-13 09:16:55 +00004440void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4441 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4442 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004443 assert(Cand->Function && "for now, candidate must be a function");
4444 FunctionDecl *Fn = Cand->Function;
4445
4446 // There's a conversion slot for the object argument if this is a
4447 // non-constructor method. Note that 'I' corresponds the
4448 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004449 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004450 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004451 if (I == 0)
4452 isObjectArgument = true;
4453 else
4454 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004455 }
4456
John McCalle1ac8d12010-01-13 00:25:19 +00004457 std::string FnDesc;
4458 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4459
John McCall6a61b522010-01-13 09:16:55 +00004460 Expr *FromExpr = Conv.Bad.FromExpr;
4461 QualType FromTy = Conv.Bad.getFromType();
4462 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004463
John McCallfb7ad0f2010-02-02 02:42:52 +00004464 if (FromTy == S.Context.OverloadTy) {
4465 assert(FromExpr);
4466 Expr *E = FromExpr->IgnoreParens();
4467 if (isa<UnaryOperator>(E))
4468 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004469 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004470
4471 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4472 << (unsigned) FnKind << FnDesc
4473 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4474 << ToTy << Name << I+1;
4475 return;
4476 }
4477
John McCall6d174642010-01-23 08:10:49 +00004478 // Do some hand-waving analysis to see if the non-viability is due
4479 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004480 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4481 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4482 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4483 CToTy = RT->getPointeeType();
4484 else {
4485 // TODO: detect and diagnose the full richness of const mismatches.
4486 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4487 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4488 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4489 }
4490
4491 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4492 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4493 // It is dumb that we have to do this here.
4494 while (isa<ArrayType>(CFromTy))
4495 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4496 while (isa<ArrayType>(CToTy))
4497 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4498
4499 Qualifiers FromQs = CFromTy.getQualifiers();
4500 Qualifiers ToQs = CToTy.getQualifiers();
4501
4502 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4503 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4504 << (unsigned) FnKind << FnDesc
4505 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4506 << FromTy
4507 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4508 << (unsigned) isObjectArgument << I+1;
4509 return;
4510 }
4511
4512 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4513 assert(CVR && "unexpected qualifiers mismatch");
4514
4515 if (isObjectArgument) {
4516 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4517 << (unsigned) FnKind << FnDesc
4518 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4519 << FromTy << (CVR - 1);
4520 } else {
4521 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4522 << (unsigned) FnKind << FnDesc
4523 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4524 << FromTy << (CVR - 1) << I+1;
4525 }
4526 return;
4527 }
4528
John McCall6d174642010-01-23 08:10:49 +00004529 // Diagnose references or pointers to incomplete types differently,
4530 // since it's far from impossible that the incompleteness triggered
4531 // the failure.
4532 QualType TempFromTy = FromTy.getNonReferenceType();
4533 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4534 TempFromTy = PTy->getPointeeType();
4535 if (TempFromTy->isIncompleteType()) {
4536 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4537 << (unsigned) FnKind << FnDesc
4538 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4539 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4540 return;
4541 }
4542
John McCall47000992010-01-14 03:28:57 +00004543 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004544 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4545 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004546 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004547 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004548}
4549
4550void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4551 unsigned NumFormalArgs) {
4552 // TODO: treat calls to a missing default constructor as a special case
4553
4554 FunctionDecl *Fn = Cand->Function;
4555 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4556
4557 unsigned MinParams = Fn->getMinRequiredArguments();
4558
4559 // at least / at most / exactly
4560 unsigned mode, modeCount;
4561 if (NumFormalArgs < MinParams) {
4562 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4563 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4564 mode = 0; // "at least"
4565 else
4566 mode = 2; // "exactly"
4567 modeCount = MinParams;
4568 } else {
4569 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4570 if (MinParams != FnTy->getNumArgs())
4571 mode = 1; // "at most"
4572 else
4573 mode = 2; // "exactly"
4574 modeCount = FnTy->getNumArgs();
4575 }
4576
4577 std::string Description;
4578 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4579
4580 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4581 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004582}
4583
John McCall8b9ed552010-02-01 18:53:26 +00004584/// Diagnose a failed template-argument deduction.
4585void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4586 Expr **Args, unsigned NumArgs) {
4587 FunctionDecl *Fn = Cand->Function; // pattern
4588
4589 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4590 Cand->DeductionFailure.TemplateParameter);
4591
4592 switch (Cand->DeductionFailure.Result) {
4593 case Sema::TDK_Success:
4594 llvm_unreachable("TDK_success while diagnosing bad deduction");
4595
4596 case Sema::TDK_Incomplete: {
4597 NamedDecl *ParamD;
4598 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4599 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4600 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4601 assert(ParamD && "no parameter found for incomplete deduction result");
4602 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4603 << ParamD->getDeclName();
4604 return;
4605 }
4606
4607 // TODO: diagnose these individually, then kill off
4608 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4609 case Sema::TDK_InstantiationDepth:
4610 case Sema::TDK_Inconsistent:
4611 case Sema::TDK_InconsistentQuals:
4612 case Sema::TDK_SubstitutionFailure:
4613 case Sema::TDK_NonDeducedMismatch:
4614 case Sema::TDK_TooManyArguments:
4615 case Sema::TDK_TooFewArguments:
4616 case Sema::TDK_InvalidExplicitArguments:
4617 case Sema::TDK_FailedOverloadResolution:
4618 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4619 return;
4620 }
4621}
4622
4623/// Generates a 'note' diagnostic for an overload candidate. We've
4624/// already generated a primary error at the call site.
4625///
4626/// It really does need to be a single diagnostic with its caret
4627/// pointed at the candidate declaration. Yes, this creates some
4628/// major challenges of technical writing. Yes, this makes pointing
4629/// out problems with specific arguments quite awkward. It's still
4630/// better than generating twenty screens of text for every failed
4631/// overload.
4632///
4633/// It would be great to be able to express per-candidate problems
4634/// more richly for those diagnostic clients that cared, but we'd
4635/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004636void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4637 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004638 FunctionDecl *Fn = Cand->Function;
4639
John McCall12f97bc2010-01-08 04:41:39 +00004640 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004641 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004642 std::string FnDesc;
4643 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004644
4645 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004646 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004647 return;
John McCall12f97bc2010-01-08 04:41:39 +00004648 }
4649
John McCalle1ac8d12010-01-13 00:25:19 +00004650 // We don't really have anything else to say about viable candidates.
4651 if (Cand->Viable) {
4652 S.NoteOverloadCandidate(Fn);
4653 return;
4654 }
John McCall0d1da222010-01-12 00:44:57 +00004655
John McCall6a61b522010-01-13 09:16:55 +00004656 switch (Cand->FailureKind) {
4657 case ovl_fail_too_many_arguments:
4658 case ovl_fail_too_few_arguments:
4659 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004660
John McCall6a61b522010-01-13 09:16:55 +00004661 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004662 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4663
John McCallfe796dd2010-01-23 05:17:32 +00004664 case ovl_fail_trivial_conversion:
4665 case ovl_fail_bad_final_conversion:
John McCall6a61b522010-01-13 09:16:55 +00004666 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004667
John McCall6a61b522010-01-13 09:16:55 +00004668 case ovl_fail_bad_conversion:
4669 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4670 if (Cand->Conversions[I].isBad())
4671 return DiagnoseBadConversion(S, Cand, I);
4672
4673 // FIXME: this currently happens when we're called from SemaInit
4674 // when user-conversion overload fails. Figure out how to handle
4675 // those conditions and diagnose them well.
4676 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004677 }
John McCalld3224162010-01-08 00:58:21 +00004678}
4679
4680void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4681 // Desugar the type of the surrogate down to a function type,
4682 // retaining as many typedefs as possible while still showing
4683 // the function type (and, therefore, its parameter types).
4684 QualType FnType = Cand->Surrogate->getConversionType();
4685 bool isLValueReference = false;
4686 bool isRValueReference = false;
4687 bool isPointer = false;
4688 if (const LValueReferenceType *FnTypeRef =
4689 FnType->getAs<LValueReferenceType>()) {
4690 FnType = FnTypeRef->getPointeeType();
4691 isLValueReference = true;
4692 } else if (const RValueReferenceType *FnTypeRef =
4693 FnType->getAs<RValueReferenceType>()) {
4694 FnType = FnTypeRef->getPointeeType();
4695 isRValueReference = true;
4696 }
4697 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4698 FnType = FnTypePtr->getPointeeType();
4699 isPointer = true;
4700 }
4701 // Desugar down to a function type.
4702 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4703 // Reconstruct the pointer/reference as appropriate.
4704 if (isPointer) FnType = S.Context.getPointerType(FnType);
4705 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4706 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4707
4708 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4709 << FnType;
4710}
4711
4712void NoteBuiltinOperatorCandidate(Sema &S,
4713 const char *Opc,
4714 SourceLocation OpLoc,
4715 OverloadCandidate *Cand) {
4716 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4717 std::string TypeStr("operator");
4718 TypeStr += Opc;
4719 TypeStr += "(";
4720 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4721 if (Cand->Conversions.size() == 1) {
4722 TypeStr += ")";
4723 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4724 } else {
4725 TypeStr += ", ";
4726 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4727 TypeStr += ")";
4728 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4729 }
4730}
4731
4732void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4733 OverloadCandidate *Cand) {
4734 unsigned NoOperands = Cand->Conversions.size();
4735 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4736 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004737 if (ICS.isBad()) break; // all meaningless after first invalid
4738 if (!ICS.isAmbiguous()) continue;
4739
4740 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4741 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004742 }
4743}
4744
John McCall3712d9e2010-01-15 23:32:50 +00004745SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4746 if (Cand->Function)
4747 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00004748 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00004749 return Cand->Surrogate->getLocation();
4750 return SourceLocation();
4751}
4752
John McCallad2587a2010-01-12 00:48:53 +00004753struct CompareOverloadCandidatesForDisplay {
4754 Sema &S;
4755 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004756
4757 bool operator()(const OverloadCandidate *L,
4758 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00004759 // Fast-path this check.
4760 if (L == R) return false;
4761
John McCall12f97bc2010-01-08 04:41:39 +00004762 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004763 if (L->Viable) {
4764 if (!R->Viable) return true;
4765
4766 // TODO: introduce a tri-valued comparison for overload
4767 // candidates. Would be more worthwhile if we had a sort
4768 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00004769 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4770 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00004771 } else if (R->Viable)
4772 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004773
John McCall3712d9e2010-01-15 23:32:50 +00004774 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004775
John McCall3712d9e2010-01-15 23:32:50 +00004776 // Criteria by which we can sort non-viable candidates:
4777 if (!L->Viable) {
4778 // 1. Arity mismatches come after other candidates.
4779 if (L->FailureKind == ovl_fail_too_many_arguments ||
4780 L->FailureKind == ovl_fail_too_few_arguments)
4781 return false;
4782 if (R->FailureKind == ovl_fail_too_many_arguments ||
4783 R->FailureKind == ovl_fail_too_few_arguments)
4784 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004785
John McCallfe796dd2010-01-23 05:17:32 +00004786 // 2. Bad conversions come first and are ordered by the number
4787 // of bad conversions and quality of good conversions.
4788 if (L->FailureKind == ovl_fail_bad_conversion) {
4789 if (R->FailureKind != ovl_fail_bad_conversion)
4790 return true;
4791
4792 // If there's any ordering between the defined conversions...
4793 // FIXME: this might not be transitive.
4794 assert(L->Conversions.size() == R->Conversions.size());
4795
4796 int leftBetter = 0;
4797 for (unsigned I = 0, E = L->Conversions.size(); I != E; ++I) {
4798 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4799 R->Conversions[I])) {
4800 case ImplicitConversionSequence::Better:
4801 leftBetter++;
4802 break;
4803
4804 case ImplicitConversionSequence::Worse:
4805 leftBetter--;
4806 break;
4807
4808 case ImplicitConversionSequence::Indistinguishable:
4809 break;
4810 }
4811 }
4812 if (leftBetter > 0) return true;
4813 if (leftBetter < 0) return false;
4814
4815 } else if (R->FailureKind == ovl_fail_bad_conversion)
4816 return false;
4817
John McCall3712d9e2010-01-15 23:32:50 +00004818 // TODO: others?
4819 }
4820
4821 // Sort everything else by location.
4822 SourceLocation LLoc = GetLocationForCandidate(L);
4823 SourceLocation RLoc = GetLocationForCandidate(R);
4824
4825 // Put candidates without locations (e.g. builtins) at the end.
4826 if (LLoc.isInvalid()) return false;
4827 if (RLoc.isInvalid()) return true;
4828
4829 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004830 }
4831};
4832
John McCallfe796dd2010-01-23 05:17:32 +00004833/// CompleteNonViableCandidate - Normally, overload resolution only
4834/// computes up to the first
4835void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4836 Expr **Args, unsigned NumArgs) {
4837 assert(!Cand->Viable);
4838
4839 // Don't do anything on failures other than bad conversion.
4840 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4841
4842 // Skip forward to the first bad conversion.
4843 unsigned ConvIdx = 0;
4844 unsigned ConvCount = Cand->Conversions.size();
4845 while (true) {
4846 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4847 ConvIdx++;
4848 if (Cand->Conversions[ConvIdx - 1].isBad())
4849 break;
4850 }
4851
4852 if (ConvIdx == ConvCount)
4853 return;
4854
4855 // FIXME: these should probably be preserved from the overload
4856 // operation somehow.
4857 bool SuppressUserConversions = false;
4858 bool ForceRValue = false;
4859
4860 const FunctionProtoType* Proto;
4861 unsigned ArgIdx = ConvIdx;
4862
4863 if (Cand->IsSurrogate) {
4864 QualType ConvType
4865 = Cand->Surrogate->getConversionType().getNonReferenceType();
4866 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4867 ConvType = ConvPtrType->getPointeeType();
4868 Proto = ConvType->getAs<FunctionProtoType>();
4869 ArgIdx--;
4870 } else if (Cand->Function) {
4871 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4872 if (isa<CXXMethodDecl>(Cand->Function) &&
4873 !isa<CXXConstructorDecl>(Cand->Function))
4874 ArgIdx--;
4875 } else {
4876 // Builtin binary operator with a bad first conversion.
4877 assert(ConvCount <= 3);
4878 for (; ConvIdx != ConvCount; ++ConvIdx)
4879 Cand->Conversions[ConvIdx]
4880 = S.TryCopyInitialization(Args[ConvIdx],
4881 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4882 SuppressUserConversions, ForceRValue,
4883 /*InOverloadResolution*/ true);
4884 return;
4885 }
4886
4887 // Fill in the rest of the conversions.
4888 unsigned NumArgsInProto = Proto->getNumArgs();
4889 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4890 if (ArgIdx < NumArgsInProto)
4891 Cand->Conversions[ConvIdx]
4892 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4893 SuppressUserConversions, ForceRValue,
4894 /*InOverloadResolution=*/true);
4895 else
4896 Cand->Conversions[ConvIdx].setEllipsis();
4897 }
4898}
4899
John McCalld3224162010-01-08 00:58:21 +00004900} // end anonymous namespace
4901
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004902/// PrintOverloadCandidates - When overload resolution fails, prints
4903/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004904/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004905void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004906Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004907 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004908 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004909 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004910 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004911 // Sort the candidates by viability and position. Sorting directly would
4912 // be prohibitive, so we make a set of pointers and sort those.
4913 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4914 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4915 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4916 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00004917 Cand != LastCand; ++Cand) {
4918 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00004919 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00004920 else if (OCD == OCD_AllCandidates) {
4921 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4922 Cands.push_back(Cand);
4923 }
4924 }
4925
John McCallad2587a2010-01-12 00:48:53 +00004926 std::sort(Cands.begin(), Cands.end(),
4927 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004928
John McCall0d1da222010-01-12 00:44:57 +00004929 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004930
John McCall12f97bc2010-01-08 04:41:39 +00004931 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4932 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4933 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004934
John McCalld3224162010-01-08 00:58:21 +00004935 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004936 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004937 else if (Cand->IsSurrogate)
4938 NoteSurrogateCandidate(*this, Cand);
4939
4940 // This a builtin candidate. We do not, in general, want to list
4941 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004942 else if (Cand->Viable) {
4943 // Generally we only see ambiguities including viable builtin
4944 // operators if overload resolution got screwed up by an
4945 // ambiguous user-defined conversion.
4946 //
4947 // FIXME: It's quite possible for different conversions to see
4948 // different ambiguities, though.
4949 if (!ReportedAmbiguousConversions) {
4950 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4951 ReportedAmbiguousConversions = true;
4952 }
John McCalld3224162010-01-08 00:58:21 +00004953
John McCall0d1da222010-01-12 00:44:57 +00004954 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004955 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004956 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004957 }
4958}
4959
John McCall1acbbb52010-02-02 06:20:04 +00004960static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, NamedDecl *D,
John McCall58cc69d2010-01-27 01:50:18 +00004961 AccessSpecifier AS) {
4962 if (isa<UnresolvedLookupExpr>(E))
4963 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D, AS);
4964
4965 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D, AS);
4966}
4967
Douglas Gregorcd695e52008-11-10 20:40:00 +00004968/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4969/// an overloaded function (C++ [over.over]), where @p From is an
4970/// expression with overloaded function type and @p ToType is the type
4971/// we're trying to resolve to. For example:
4972///
4973/// @code
4974/// int f(double);
4975/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004976///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004977/// int (*pfd)(double) = f; // selects f(double)
4978/// @endcode
4979///
4980/// This routine returns the resulting FunctionDecl if it could be
4981/// resolved, and NULL otherwise. When @p Complain is true, this
4982/// routine will emit diagnostics if there is an error.
4983FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004984Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004985 bool Complain) {
4986 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004987 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004988 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004989 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004990 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004991 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004992 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004993 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004994 FunctionType = MemTypePtr->getPointeeType();
4995 IsMember = true;
4996 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004997
4998 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004999 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00005000 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005001 return 0;
5002
5003 // Find the actual overloaded function declaration.
John McCall1acbbb52010-02-02 06:20:04 +00005004 if (From->getType() != Context.OverloadTy)
5005 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005006
Douglas Gregorcd695e52008-11-10 20:40:00 +00005007 // C++ [over.over]p1:
5008 // [...] [Note: any redundant set of parentheses surrounding the
5009 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005010 // C++ [over.over]p1:
5011 // [...] The overloaded function name can be preceded by the &
5012 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005013 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5014 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5015 if (OvlExpr->hasExplicitTemplateArgs()) {
5016 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5017 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005018 }
5019
Douglas Gregorcd695e52008-11-10 20:40:00 +00005020 // Look through all of the overloaded functions, searching for one
5021 // whose type matches exactly.
John McCall58cc69d2010-01-27 01:50:18 +00005022 UnresolvedSet<4> Matches; // contains only FunctionDecls
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005023 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005024 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5025 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005026 // Look through any using declarations to find the underlying function.
5027 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5028
Douglas Gregorcd695e52008-11-10 20:40:00 +00005029 // C++ [over.over]p3:
5030 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005031 // targets of type "pointer-to-function" or "reference-to-function."
5032 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005033 // type "pointer-to-member-function."
5034 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005035
Mike Stump11289f42009-09-09 15:08:12 +00005036 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005037 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005038 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005039 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005040 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005041 // static when converting to member pointer.
5042 if (Method->isStatic() == IsMember)
5043 continue;
5044 } else if (IsMember)
5045 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005046
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005047 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005048 // If the name is a function template, template argument deduction is
5049 // done (14.8.2.2), and if the argument deduction succeeds, the
5050 // resulting template argument list is used to generate a single
5051 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005052 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005053 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005054 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005055 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005056 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005057 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005058 FunctionType, Specialization, Info)) {
5059 // FIXME: make a note of the failed deduction for diagnostics.
5060 (void)Result;
5061 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005062 // FIXME: If the match isn't exact, shouldn't we just drop this as
5063 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005064 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005065 == Context.getCanonicalType(Specialization->getType()));
John McCall58cc69d2010-01-27 01:50:18 +00005066 Matches.addDecl(cast<FunctionDecl>(Specialization->getCanonicalDecl()),
5067 I.getAccess());
Douglas Gregor9b146582009-07-08 20:55:45 +00005068 }
John McCalld14a8642009-11-21 08:51:07 +00005069
5070 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005071 }
Mike Stump11289f42009-09-09 15:08:12 +00005072
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005073 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005074 // Skip non-static functions when converting to pointer, and static
5075 // when converting to member pointer.
5076 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005077 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005078
5079 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005080 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005081 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005082 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005083 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005084
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005085 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005086 QualType ResultTy;
5087 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5088 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5089 ResultTy)) {
John McCall58cc69d2010-01-27 01:50:18 +00005090 Matches.addDecl(cast<FunctionDecl>(FunDecl->getCanonicalDecl()),
5091 I.getAccess());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005092 FoundNonTemplateFunction = true;
5093 }
Mike Stump11289f42009-09-09 15:08:12 +00005094 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005095 }
5096
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005097 // If there were 0 or 1 matches, we're done.
5098 if (Matches.empty())
5099 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005100 else if (Matches.size() == 1) {
John McCall58cc69d2010-01-27 01:50:18 +00005101 FunctionDecl *Result = cast<FunctionDecl>(*Matches.begin());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005102 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005103 if (Complain)
5104 CheckUnresolvedAccess(*this, OvlExpr, Result, Matches.begin().getAccess());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005105 return Result;
5106 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005107
5108 // C++ [over.over]p4:
5109 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005110 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005111 // [...] and any given function template specialization F1 is
5112 // eliminated if the set contains a second function template
5113 // specialization whose function template is more specialized
5114 // than the function template of F1 according to the partial
5115 // ordering rules of 14.5.5.2.
5116
5117 // The algorithm specified above is quadratic. We instead use a
5118 // two-pass algorithm (similar to the one used to identify the
5119 // best viable function in an overload set) that identifies the
5120 // best function template (if it exists).
John McCall58cc69d2010-01-27 01:50:18 +00005121
5122 UnresolvedSetIterator Result =
5123 getMostSpecialized(Matches.begin(), Matches.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005124 TPOC_Other, From->getLocStart(),
5125 PDiag(),
5126 PDiag(diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005127 << Matches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005128 PDiag(diag::note_ovl_candidate)
5129 << (unsigned) oc_function_template);
John McCall58cc69d2010-01-27 01:50:18 +00005130 assert(Result != Matches.end() && "no most-specialized template");
5131 MarkDeclarationReferenced(From->getLocStart(), *Result);
5132 if (Complain)
5133 CheckUnresolvedAccess(*this, OvlExpr, *Result, Result.getAccess());
5134 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005135 }
Mike Stump11289f42009-09-09 15:08:12 +00005136
Douglas Gregorfae1d712009-09-26 03:56:17 +00005137 // [...] any function template specializations in the set are
5138 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005139 for (unsigned I = 0, N = Matches.size(); I != N; ) {
5140 if (cast<FunctionDecl>(Matches[I].getDecl())->getPrimaryTemplate() == 0)
5141 ++I;
5142 else {
5143 Matches.erase(I);
5144 --N;
5145 }
5146 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005147
Mike Stump11289f42009-09-09 15:08:12 +00005148 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005149 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005150 if (Matches.size() == 1) {
5151 UnresolvedSetIterator Match = Matches.begin();
5152 MarkDeclarationReferenced(From->getLocStart(), *Match);
5153 if (Complain)
5154 CheckUnresolvedAccess(*this, OvlExpr, *Match, Match.getAccess());
5155 return cast<FunctionDecl>(*Match);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005156 }
Mike Stump11289f42009-09-09 15:08:12 +00005157
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005158 // FIXME: We should probably return the same thing that BestViableFunction
5159 // returns (even if we issue the diagnostics here).
5160 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005161 << Matches[0]->getDeclName();
5162 for (UnresolvedSetIterator I = Matches.begin(),
5163 E = Matches.end(); I != E; ++I)
5164 NoteOverloadCandidate(cast<FunctionDecl>(*I));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005165 return 0;
5166}
5167
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005168/// \brief Given an expression that refers to an overloaded function, try to
5169/// resolve that overloaded function expression down to a single function.
5170///
5171/// This routine can only resolve template-ids that refer to a single function
5172/// template, where that template-id refers to a single template whose template
5173/// arguments are either provided by the template-id or have defaults,
5174/// as described in C++0x [temp.arg.explicit]p3.
5175FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5176 // C++ [over.over]p1:
5177 // [...] [Note: any redundant set of parentheses surrounding the
5178 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005179 // C++ [over.over]p1:
5180 // [...] The overloaded function name can be preceded by the &
5181 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005182
5183 if (From->getType() != Context.OverloadTy)
5184 return 0;
5185
5186 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005187
5188 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005189 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005190 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005191
5192 TemplateArgumentListInfo ExplicitTemplateArgs;
5193 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005194
5195 // Look through all of the overloaded functions, searching for one
5196 // whose type matches exactly.
5197 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005198 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5199 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005200 // C++0x [temp.arg.explicit]p3:
5201 // [...] In contexts where deduction is done and fails, or in contexts
5202 // where deduction is not done, if a template argument list is
5203 // specified and it, along with any default template arguments,
5204 // identifies a single function template specialization, then the
5205 // template-id is an lvalue for the function template specialization.
5206 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5207
5208 // C++ [over.over]p2:
5209 // If the name is a function template, template argument deduction is
5210 // done (14.8.2.2), and if the argument deduction succeeds, the
5211 // resulting template argument list is used to generate a single
5212 // function template specialization, which is added to the set of
5213 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005214 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005215 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005216 if (TemplateDeductionResult Result
5217 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5218 Specialization, Info)) {
5219 // FIXME: make a note of the failed deduction for diagnostics.
5220 (void)Result;
5221 continue;
5222 }
5223
5224 // Multiple matches; we can't resolve to a single declaration.
5225 if (Matched)
5226 return 0;
5227
5228 Matched = Specialization;
5229 }
5230
5231 return Matched;
5232}
5233
Douglas Gregorcabea402009-09-22 15:41:20 +00005234/// \brief Add a single candidate to the overload set.
5235static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00005236 NamedDecl *Callee,
John McCallb89836b2010-01-26 01:37:31 +00005237 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00005238 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005239 Expr **Args, unsigned NumArgs,
5240 OverloadCandidateSet &CandidateSet,
5241 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005242 if (isa<UsingShadowDecl>(Callee))
5243 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5244
Douglas Gregorcabea402009-09-22 15:41:20 +00005245 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005246 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCallb89836b2010-01-26 01:37:31 +00005247 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5248 false, false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005249 return;
John McCalld14a8642009-11-21 08:51:07 +00005250 }
5251
5252 if (FunctionTemplateDecl *FuncTemplate
5253 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCallb89836b2010-01-26 01:37:31 +00005254 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005255 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005256 return;
5257 }
5258
5259 assert(false && "unhandled case in overloaded call candidate");
5260
5261 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005262}
5263
5264/// \brief Add the overload candidates named by callee and/or found by argument
5265/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005266void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005267 Expr **Args, unsigned NumArgs,
5268 OverloadCandidateSet &CandidateSet,
5269 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005270
5271#ifndef NDEBUG
5272 // Verify that ArgumentDependentLookup is consistent with the rules
5273 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005274 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005275 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5276 // and let Y be the lookup set produced by argument dependent
5277 // lookup (defined as follows). If X contains
5278 //
5279 // -- a declaration of a class member, or
5280 //
5281 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005282 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005283 //
5284 // -- a declaration that is neither a function or a function
5285 // template
5286 //
5287 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005288
John McCall57500772009-12-16 12:17:52 +00005289 if (ULE->requiresADL()) {
5290 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5291 E = ULE->decls_end(); I != E; ++I) {
5292 assert(!(*I)->getDeclContext()->isRecord());
5293 assert(isa<UsingShadowDecl>(*I) ||
5294 !(*I)->getDeclContext()->isFunctionOrMethod());
5295 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005296 }
5297 }
5298#endif
5299
John McCall57500772009-12-16 12:17:52 +00005300 // It would be nice to avoid this copy.
5301 TemplateArgumentListInfo TABuffer;
5302 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5303 if (ULE->hasExplicitTemplateArgs()) {
5304 ULE->copyTemplateArgumentsInto(TABuffer);
5305 ExplicitTemplateArgs = &TABuffer;
5306 }
5307
5308 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5309 E = ULE->decls_end(); I != E; ++I)
John McCallb89836b2010-01-26 01:37:31 +00005310 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005311 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005312 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005313
John McCall57500772009-12-16 12:17:52 +00005314 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005315 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5316 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005317 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005318 CandidateSet,
5319 PartialOverloading);
5320}
John McCalld681c392009-12-16 08:11:27 +00005321
John McCall57500772009-12-16 12:17:52 +00005322static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5323 Expr **Args, unsigned NumArgs) {
5324 Fn->Destroy(SemaRef.Context);
5325 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5326 Args[Arg]->Destroy(SemaRef.Context);
5327 return SemaRef.ExprError();
5328}
5329
John McCalld681c392009-12-16 08:11:27 +00005330/// Attempts to recover from a call where no functions were found.
5331///
5332/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005333static Sema::OwningExprResult
5334BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5335 UnresolvedLookupExpr *ULE,
5336 SourceLocation LParenLoc,
5337 Expr **Args, unsigned NumArgs,
5338 SourceLocation *CommaLocs,
5339 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005340
5341 CXXScopeSpec SS;
5342 if (ULE->getQualifier()) {
5343 SS.setScopeRep(ULE->getQualifier());
5344 SS.setRange(ULE->getQualifierRange());
5345 }
5346
John McCall57500772009-12-16 12:17:52 +00005347 TemplateArgumentListInfo TABuffer;
5348 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5349 if (ULE->hasExplicitTemplateArgs()) {
5350 ULE->copyTemplateArgumentsInto(TABuffer);
5351 ExplicitTemplateArgs = &TABuffer;
5352 }
5353
John McCalld681c392009-12-16 08:11:27 +00005354 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5355 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005356 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005357 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005358
John McCall57500772009-12-16 12:17:52 +00005359 assert(!R.empty() && "lookup results empty despite recovery");
5360
5361 // Build an implicit member call if appropriate. Just drop the
5362 // casts and such from the call, we don't really care.
5363 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5364 if ((*R.begin())->isCXXClassMember())
5365 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5366 else if (ExplicitTemplateArgs)
5367 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5368 else
5369 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5370
5371 if (NewFn.isInvalid())
5372 return Destroy(SemaRef, Fn, Args, NumArgs);
5373
5374 Fn->Destroy(SemaRef.Context);
5375
5376 // This shouldn't cause an infinite loop because we're giving it
5377 // an expression with non-empty lookup results, which should never
5378 // end up here.
5379 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5380 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5381 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005382}
Douglas Gregorcabea402009-09-22 15:41:20 +00005383
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005384/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005385/// (which eventually refers to the declaration Func) and the call
5386/// arguments Args/NumArgs, attempt to resolve the function call down
5387/// to a specific function. If overload resolution succeeds, returns
5388/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005389/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005390/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005391Sema::OwningExprResult
5392Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5393 SourceLocation LParenLoc,
5394 Expr **Args, unsigned NumArgs,
5395 SourceLocation *CommaLocs,
5396 SourceLocation RParenLoc) {
5397#ifndef NDEBUG
5398 if (ULE->requiresADL()) {
5399 // To do ADL, we must have found an unqualified name.
5400 assert(!ULE->getQualifier() && "qualified name with ADL");
5401
5402 // We don't perform ADL for implicit declarations of builtins.
5403 // Verify that this was correctly set up.
5404 FunctionDecl *F;
5405 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5406 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5407 F->getBuiltinID() && F->isImplicit())
5408 assert(0 && "performing ADL for builtin");
5409
5410 // We don't perform ADL in C.
5411 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5412 }
5413#endif
5414
John McCallbc077cf2010-02-08 23:07:23 +00005415 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005416
John McCall57500772009-12-16 12:17:52 +00005417 // Add the functions denoted by the callee to the set of candidate
5418 // functions, including those from argument-dependent lookup.
5419 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005420
5421 // If we found nothing, try to recover.
5422 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5423 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005424 if (CandidateSet.empty())
5425 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5426 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005427
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005428 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005429 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005430 case OR_Success: {
5431 FunctionDecl *FDecl = Best->Function;
John McCall58cc69d2010-01-27 01:50:18 +00005432 CheckUnresolvedLookupAccess(ULE, FDecl, Best->getAccess());
John McCall57500772009-12-16 12:17:52 +00005433 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5434 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5435 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005436
5437 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005438 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005439 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005440 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005441 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005442 break;
5443
5444 case OR_Ambiguous:
5445 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005446 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005447 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005448 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005449
5450 case OR_Deleted:
5451 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5452 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005453 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005454 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005455 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005456 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005457 }
5458
5459 // Overload resolution failed. Destroy all of the subexpressions and
5460 // return NULL.
5461 Fn->Destroy(Context);
5462 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5463 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005464 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005465}
5466
John McCall4c4c1df2010-01-26 03:27:55 +00005467static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005468 return Functions.size() > 1 ||
5469 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5470}
5471
Douglas Gregor084d8552009-03-13 23:49:33 +00005472/// \brief Create a unary operation that may resolve to an overloaded
5473/// operator.
5474///
5475/// \param OpLoc The location of the operator itself (e.g., '*').
5476///
5477/// \param OpcIn The UnaryOperator::Opcode that describes this
5478/// operator.
5479///
5480/// \param Functions The set of non-member functions that will be
5481/// considered by overload resolution. The caller needs to build this
5482/// set based on the context using, e.g.,
5483/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5484/// set should not contain any member functions; those will be added
5485/// by CreateOverloadedUnaryOp().
5486///
5487/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005488Sema::OwningExprResult
5489Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5490 const UnresolvedSetImpl &Fns,
5491 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005492 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5493 Expr *Input = (Expr *)input.get();
5494
5495 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5496 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5497 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5498
5499 Expr *Args[2] = { Input, 0 };
5500 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005501
Douglas Gregor084d8552009-03-13 23:49:33 +00005502 // For post-increment and post-decrement, add the implicit '0' as
5503 // the second argument, so that we know this is a post-increment or
5504 // post-decrement.
5505 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5506 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005507 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005508 SourceLocation());
5509 NumArgs = 2;
5510 }
5511
5512 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005513 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005514 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005515 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005516 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005517 /*ADL*/ true, IsOverloaded(Fns));
5518 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005519
Douglas Gregor084d8552009-03-13 23:49:33 +00005520 input.release();
5521 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5522 &Args[0], NumArgs,
5523 Context.DependentTy,
5524 OpLoc));
5525 }
5526
5527 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005528 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005529
5530 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005531 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005532
5533 // Add operator candidates that are member functions.
5534 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5535
John McCall4c4c1df2010-01-26 03:27:55 +00005536 // Add candidates from ADL.
5537 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005538 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005539 /*ExplicitTemplateArgs*/ 0,
5540 CandidateSet);
5541
Douglas Gregor084d8552009-03-13 23:49:33 +00005542 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005543 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005544
5545 // Perform overload resolution.
5546 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005547 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005548 case OR_Success: {
5549 // We found a built-in operator or an overloaded operator.
5550 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005551
Douglas Gregor084d8552009-03-13 23:49:33 +00005552 if (FnDecl) {
5553 // We matched an overloaded operator. Build a call to that
5554 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005555
Douglas Gregor084d8552009-03-13 23:49:33 +00005556 // Convert the arguments.
5557 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005558 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5559
Douglas Gregor084d8552009-03-13 23:49:33 +00005560 if (PerformObjectArgumentInitialization(Input, Method))
5561 return ExprError();
5562 } else {
5563 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005564 OwningExprResult InputInit
5565 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005566 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005567 SourceLocation(),
5568 move(input));
5569 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005570 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005571
Douglas Gregore6600372009-12-23 17:40:29 +00005572 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005573 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005574 }
5575
5576 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005577 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005578
Douglas Gregor084d8552009-03-13 23:49:33 +00005579 // Build the actual expression node.
5580 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5581 SourceLocation());
5582 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005583
Douglas Gregor084d8552009-03-13 23:49:33 +00005584 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005585 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005586 ExprOwningPtr<CallExpr> TheCall(this,
5587 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005588 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005589
5590 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5591 FnDecl))
5592 return ExprError();
5593
5594 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005595 } else {
5596 // We matched a built-in operator. Convert the arguments, then
5597 // break out so that we will build the appropriate built-in
5598 // operator node.
5599 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005600 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005601 return ExprError();
5602
5603 break;
5604 }
5605 }
5606
5607 case OR_No_Viable_Function:
5608 // No viable function; fall through to handling this as a
5609 // built-in operator, which will produce an error message for us.
5610 break;
5611
5612 case OR_Ambiguous:
5613 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5614 << UnaryOperator::getOpcodeStr(Opc)
5615 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005616 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005617 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005618 return ExprError();
5619
5620 case OR_Deleted:
5621 Diag(OpLoc, diag::err_ovl_deleted_oper)
5622 << Best->Function->isDeleted()
5623 << UnaryOperator::getOpcodeStr(Opc)
5624 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005625 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005626 return ExprError();
5627 }
5628
5629 // Either we found no viable overloaded operator or we matched a
5630 // built-in operator. In either case, fall through to trying to
5631 // build a built-in operation.
5632 input.release();
5633 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5634}
5635
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005636/// \brief Create a binary operation that may resolve to an overloaded
5637/// operator.
5638///
5639/// \param OpLoc The location of the operator itself (e.g., '+').
5640///
5641/// \param OpcIn The BinaryOperator::Opcode that describes this
5642/// operator.
5643///
5644/// \param Functions The set of non-member functions that will be
5645/// considered by overload resolution. The caller needs to build this
5646/// set based on the context using, e.g.,
5647/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5648/// set should not contain any member functions; those will be added
5649/// by CreateOverloadedBinOp().
5650///
5651/// \param LHS Left-hand argument.
5652/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005653Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005654Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005655 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005656 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005657 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005658 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005659 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005660
5661 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5662 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5663 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5664
5665 // If either side is type-dependent, create an appropriate dependent
5666 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005667 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00005668 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005669 // If there are no functions to store, just build a dependent
5670 // BinaryOperator or CompoundAssignment.
5671 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5672 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5673 Context.DependentTy, OpLoc));
5674
5675 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5676 Context.DependentTy,
5677 Context.DependentTy,
5678 Context.DependentTy,
5679 OpLoc));
5680 }
John McCall4c4c1df2010-01-26 03:27:55 +00005681
5682 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00005683 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005684 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005685 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005686 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005687 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00005688
John McCall4c4c1df2010-01-26 03:27:55 +00005689 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005690 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005691 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005692 Context.DependentTy,
5693 OpLoc));
5694 }
5695
5696 // If this is the .* operator, which is not overloadable, just
5697 // create a built-in binary operator.
5698 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005699 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005700
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005701 // If this is the assignment operator, we only perform overload resolution
5702 // if the left-hand side is a class or enumeration type. This is actually
5703 // a hack. The standard requires that we do overload resolution between the
5704 // various built-in candidates, but as DR507 points out, this can lead to
5705 // problems. So we do it this way, which pretty much follows what GCC does.
5706 // Note that we go the traditional code path for compound assignment forms.
5707 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005708 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005709
Douglas Gregor084d8552009-03-13 23:49:33 +00005710 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005711 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005712
5713 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005714 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005715
5716 // Add operator candidates that are member functions.
5717 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5718
John McCall4c4c1df2010-01-26 03:27:55 +00005719 // Add candidates from ADL.
5720 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5721 Args, 2,
5722 /*ExplicitTemplateArgs*/ 0,
5723 CandidateSet);
5724
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005725 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005726 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005727
5728 // Perform overload resolution.
5729 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005730 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005731 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005732 // We found a built-in operator or an overloaded operator.
5733 FunctionDecl *FnDecl = Best->Function;
5734
5735 if (FnDecl) {
5736 // We matched an overloaded operator. Build a call to that
5737 // operator.
5738
5739 // Convert the arguments.
5740 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005741 // Best->Access is only meaningful for class members.
5742 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5743
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005744 OwningExprResult Arg1
5745 = PerformCopyInitialization(
5746 InitializedEntity::InitializeParameter(
5747 FnDecl->getParamDecl(0)),
5748 SourceLocation(),
5749 Owned(Args[1]));
5750 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005751 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005752
5753 if (PerformObjectArgumentInitialization(Args[0], Method))
5754 return ExprError();
5755
5756 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005757 } else {
5758 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005759 OwningExprResult Arg0
5760 = PerformCopyInitialization(
5761 InitializedEntity::InitializeParameter(
5762 FnDecl->getParamDecl(0)),
5763 SourceLocation(),
5764 Owned(Args[0]));
5765 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005766 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005767
5768 OwningExprResult Arg1
5769 = PerformCopyInitialization(
5770 InitializedEntity::InitializeParameter(
5771 FnDecl->getParamDecl(1)),
5772 SourceLocation(),
5773 Owned(Args[1]));
5774 if (Arg1.isInvalid())
5775 return ExprError();
5776 Args[0] = LHS = Arg0.takeAs<Expr>();
5777 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005778 }
5779
5780 // Determine the result type
5781 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005782 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005783 ResultTy = ResultTy.getNonReferenceType();
5784
5785 // Build the actual expression node.
5786 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005787 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005788 UsualUnaryConversions(FnExpr);
5789
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005790 ExprOwningPtr<CXXOperatorCallExpr>
5791 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5792 Args, 2, ResultTy,
5793 OpLoc));
5794
5795 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5796 FnDecl))
5797 return ExprError();
5798
5799 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005800 } else {
5801 // We matched a built-in operator. Convert the arguments, then
5802 // break out so that we will build the appropriate built-in
5803 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005804 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005805 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005806 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005807 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005808 return ExprError();
5809
5810 break;
5811 }
5812 }
5813
Douglas Gregor66950a32009-09-30 21:46:01 +00005814 case OR_No_Viable_Function: {
5815 // C++ [over.match.oper]p9:
5816 // If the operator is the operator , [...] and there are no
5817 // viable functions, then the operator is assumed to be the
5818 // built-in operator and interpreted according to clause 5.
5819 if (Opc == BinaryOperator::Comma)
5820 break;
5821
Sebastian Redl027de2a2009-05-21 11:50:50 +00005822 // For class as left operand for assignment or compound assigment operator
5823 // do not fall through to handling in built-in, but report that no overloaded
5824 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005825 OwningExprResult Result = ExprError();
5826 if (Args[0]->getType()->isRecordType() &&
5827 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005828 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5829 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005830 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005831 } else {
5832 // No viable function; try to create a built-in operation, which will
5833 // produce an error. Then, show the non-viable candidates.
5834 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005835 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005836 assert(Result.isInvalid() &&
5837 "C++ binary operator overloading is missing candidates!");
5838 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005839 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005840 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005841 return move(Result);
5842 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005843
5844 case OR_Ambiguous:
5845 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5846 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005847 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005848 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005849 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005850 return ExprError();
5851
5852 case OR_Deleted:
5853 Diag(OpLoc, diag::err_ovl_deleted_oper)
5854 << Best->Function->isDeleted()
5855 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005856 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005857 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005858 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005859 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005860
Douglas Gregor66950a32009-09-30 21:46:01 +00005861 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005862 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005863}
5864
Sebastian Redladba46e2009-10-29 20:17:01 +00005865Action::OwningExprResult
5866Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5867 SourceLocation RLoc,
5868 ExprArg Base, ExprArg Idx) {
5869 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5870 static_cast<Expr*>(Idx.get()) };
5871 DeclarationName OpName =
5872 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5873
5874 // If either side is type-dependent, create an appropriate dependent
5875 // expression.
5876 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5877
John McCall58cc69d2010-01-27 01:50:18 +00005878 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005879 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005880 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005881 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005882 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005883 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005884
5885 Base.release();
5886 Idx.release();
5887 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5888 Args, 2,
5889 Context.DependentTy,
5890 RLoc));
5891 }
5892
5893 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005894 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005895
5896 // Subscript can only be overloaded as a member function.
5897
5898 // Add operator candidates that are member functions.
5899 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5900
5901 // Add builtin operator candidates.
5902 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5903
5904 // Perform overload resolution.
5905 OverloadCandidateSet::iterator Best;
5906 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5907 case OR_Success: {
5908 // We found a built-in operator or an overloaded operator.
5909 FunctionDecl *FnDecl = Best->Function;
5910
5911 if (FnDecl) {
5912 // We matched an overloaded operator. Build a call to that
5913 // operator.
5914
John McCallb3a44002010-01-28 01:42:12 +00005915 CheckMemberOperatorAccess(LLoc, Args[0], FnDecl, Best->getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005916
Sebastian Redladba46e2009-10-29 20:17:01 +00005917 // Convert the arguments.
5918 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Anders Carlssona68e51e2010-01-29 18:37:50 +00005919 if (PerformObjectArgumentInitialization(Args[0], Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00005920 return ExprError();
5921
Anders Carlssona68e51e2010-01-29 18:37:50 +00005922 // Convert the arguments.
5923 OwningExprResult InputInit
5924 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5925 FnDecl->getParamDecl(0)),
5926 SourceLocation(),
5927 Owned(Args[1]));
5928 if (InputInit.isInvalid())
5929 return ExprError();
5930
5931 Args[1] = InputInit.takeAs<Expr>();
5932
Sebastian Redladba46e2009-10-29 20:17:01 +00005933 // Determine the result type
5934 QualType ResultTy
5935 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5936 ResultTy = ResultTy.getNonReferenceType();
5937
5938 // Build the actual expression node.
5939 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5940 LLoc);
5941 UsualUnaryConversions(FnExpr);
5942
5943 Base.release();
5944 Idx.release();
5945 ExprOwningPtr<CXXOperatorCallExpr>
5946 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5947 FnExpr, Args, 2,
5948 ResultTy, RLoc));
5949
5950 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5951 FnDecl))
5952 return ExprError();
5953
5954 return MaybeBindToTemporary(TheCall.release());
5955 } else {
5956 // We matched a built-in operator. Convert the arguments, then
5957 // break out so that we will build the appropriate built-in
5958 // operator node.
5959 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005960 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005961 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005962 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005963 return ExprError();
5964
5965 break;
5966 }
5967 }
5968
5969 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005970 if (CandidateSet.empty())
5971 Diag(LLoc, diag::err_ovl_no_oper)
5972 << Args[0]->getType() << /*subscript*/ 0
5973 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5974 else
5975 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5976 << Args[0]->getType()
5977 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005978 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005979 "[]", LLoc);
5980 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005981 }
5982
5983 case OR_Ambiguous:
5984 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5985 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005986 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005987 "[]", LLoc);
5988 return ExprError();
5989
5990 case OR_Deleted:
5991 Diag(LLoc, diag::err_ovl_deleted_oper)
5992 << Best->Function->isDeleted() << "[]"
5993 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005994 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005995 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005996 return ExprError();
5997 }
5998
5999 // We matched a built-in operator; build it.
6000 Base.release();
6001 Idx.release();
6002 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6003 Owned(Args[1]), RLoc);
6004}
6005
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006006/// BuildCallToMemberFunction - Build a call to a member
6007/// function. MemExpr is the expression that refers to the member
6008/// function (and includes the object parameter), Args/NumArgs are the
6009/// arguments to the function call (not including the object
6010/// parameter). The caller needs to validate that the member
6011/// expression refers to a member function or an overloaded member
6012/// function.
John McCall2d74de92009-12-01 22:10:20 +00006013Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006014Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6015 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006016 unsigned NumArgs, SourceLocation *CommaLocs,
6017 SourceLocation RParenLoc) {
6018 // Dig out the member expression. This holds both the object
6019 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006020 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6021
John McCall10eae182009-11-30 22:42:35 +00006022 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006023 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00006024 if (isa<MemberExpr>(NakedMemExpr)) {
6025 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006026 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
6027 } else {
6028 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00006029
John McCall6e9f8f62009-12-03 04:06:58 +00006030 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006031
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006032 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006033 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006034
John McCall2d74de92009-12-01 22:10:20 +00006035 // FIXME: avoid copy.
6036 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6037 if (UnresExpr->hasExplicitTemplateArgs()) {
6038 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6039 TemplateArgs = &TemplateArgsBuffer;
6040 }
6041
John McCall10eae182009-11-30 22:42:35 +00006042 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6043 E = UnresExpr->decls_end(); I != E; ++I) {
6044
John McCall6e9f8f62009-12-03 04:06:58 +00006045 NamedDecl *Func = *I;
6046 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6047 if (isa<UsingShadowDecl>(Func))
6048 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6049
John McCall10eae182009-11-30 22:42:35 +00006050 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006051 // If explicit template arguments were provided, we can't call a
6052 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006053 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006054 continue;
6055
John McCallb89836b2010-01-26 01:37:31 +00006056 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
6057 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006058 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006059 } else {
John McCall10eae182009-11-30 22:42:35 +00006060 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCallb89836b2010-01-26 01:37:31 +00006061 I.getAccess(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006062 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006063 CandidateSet,
6064 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006065 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006066 }
Mike Stump11289f42009-09-09 15:08:12 +00006067
John McCall10eae182009-11-30 22:42:35 +00006068 DeclarationName DeclName = UnresExpr->getMemberName();
6069
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006070 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006071 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006072 case OR_Success:
6073 Method = cast<CXXMethodDecl>(Best->Function);
John McCall58cc69d2010-01-27 01:50:18 +00006074 CheckUnresolvedMemberAccess(UnresExpr, Method, Best->getAccess());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006075 break;
6076
6077 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006078 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006079 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006080 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006081 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006082 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006083 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006084
6085 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006086 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006087 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006088 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006089 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006090 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006091
6092 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006093 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006094 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006095 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006096 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006097 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006098 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006099 }
6100
Douglas Gregor51c538b2009-11-20 19:42:02 +00006101 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00006102
John McCall2d74de92009-12-01 22:10:20 +00006103 // If overload resolution picked a static member, build a
6104 // non-member call based on that function.
6105 if (Method->isStatic()) {
6106 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6107 Args, NumArgs, RParenLoc);
6108 }
6109
John McCall10eae182009-11-30 22:42:35 +00006110 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006111 }
6112
6113 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006114 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006115 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006116 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006117 Method->getResultType().getNonReferenceType(),
6118 RParenLoc));
6119
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006120 // Check for a valid return type.
6121 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6122 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006123 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006124
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006125 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00006126 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006127 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006128 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00006129 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006130 MemExpr->setBase(ObjectArg);
6131
6132 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006133 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006134 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006135 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006136 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006137
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006138 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006139 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006140
John McCall2d74de92009-12-01 22:10:20 +00006141 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006142}
6143
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006144/// BuildCallToObjectOfClassType - Build a call to an object of class
6145/// type (C++ [over.call.object]), which can end up invoking an
6146/// overloaded function call operator (@c operator()) or performing a
6147/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006148Sema::ExprResult
6149Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006150 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006151 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006152 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006153 SourceLocation RParenLoc) {
6154 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006155 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006156
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006157 // C++ [over.call.object]p1:
6158 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006159 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006160 // candidate functions includes at least the function call
6161 // operators of T. The function call operators of T are obtained by
6162 // ordinary lookup of the name operator() in the context of
6163 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006164 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006165 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006166
6167 if (RequireCompleteType(LParenLoc, Object->getType(),
6168 PartialDiagnostic(diag::err_incomplete_object_call)
6169 << Object->getSourceRange()))
6170 return true;
6171
John McCall27b18f82009-11-17 02:14:36 +00006172 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6173 LookupQualifiedName(R, Record->getDecl());
6174 R.suppressDiagnostics();
6175
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006176 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006177 Oper != OperEnd; ++Oper) {
John McCallb89836b2010-01-26 01:37:31 +00006178 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6179 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006180 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006181 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006182
Douglas Gregorab7897a2008-11-19 22:57:39 +00006183 // C++ [over.call.object]p2:
6184 // In addition, for each conversion function declared in T of the
6185 // form
6186 //
6187 // operator conversion-type-id () cv-qualifier;
6188 //
6189 // where cv-qualifier is the same cv-qualification as, or a
6190 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006191 // denotes the type "pointer to function of (P1,...,Pn) returning
6192 // R", or the type "reference to pointer to function of
6193 // (P1,...,Pn) returning R", or the type "reference to function
6194 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006195 // is also considered as a candidate function. Similarly,
6196 // surrogate call functions are added to the set of candidate
6197 // functions for each conversion function declared in an
6198 // accessible base class provided the function is not hidden
6199 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006200 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006201 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006202 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006203 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006204 NamedDecl *D = *I;
6205 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6206 if (isa<UsingShadowDecl>(D))
6207 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6208
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006209 // Skip over templated conversion functions; they aren't
6210 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006211 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006212 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006213
John McCall6e9f8f62009-12-03 04:06:58 +00006214 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006215
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006216 // Strip the reference type (if any) and then the pointer type (if
6217 // any) to get down to what might be a function type.
6218 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6219 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6220 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006221
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006222 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCallb89836b2010-01-26 01:37:31 +00006223 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006224 Object->getType(), Args, NumArgs,
6225 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006226 }
Mike Stump11289f42009-09-09 15:08:12 +00006227
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006228 // Perform overload resolution.
6229 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006230 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006231 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006232 // Overload resolution succeeded; we'll build the appropriate call
6233 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006234 break;
6235
6236 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006237 if (CandidateSet.empty())
6238 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6239 << Object->getType() << /*call*/ 1
6240 << Object->getSourceRange();
6241 else
6242 Diag(Object->getSourceRange().getBegin(),
6243 diag::err_ovl_no_viable_object_call)
6244 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006245 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006246 break;
6247
6248 case OR_Ambiguous:
6249 Diag(Object->getSourceRange().getBegin(),
6250 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006251 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006252 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006253 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006254
6255 case OR_Deleted:
6256 Diag(Object->getSourceRange().getBegin(),
6257 diag::err_ovl_deleted_object_call)
6258 << Best->Function->isDeleted()
6259 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006260 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006261 break;
Mike Stump11289f42009-09-09 15:08:12 +00006262 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006263
Douglas Gregorab7897a2008-11-19 22:57:39 +00006264 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006265 // We had an error; delete all of the subexpressions and return
6266 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006267 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006268 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006269 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006270 return true;
6271 }
6272
Douglas Gregorab7897a2008-11-19 22:57:39 +00006273 if (Best->Function == 0) {
6274 // Since there is no function declaration, this is one of the
6275 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006276 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006277 = cast<CXXConversionDecl>(
6278 Best->Conversions[0].UserDefined.ConversionFunction);
6279
John McCall2cb94162010-01-28 07:38:46 +00006280 CheckMemberOperatorAccess(LParenLoc, Object, Conv, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006281
Douglas Gregorab7897a2008-11-19 22:57:39 +00006282 // We selected one of the surrogate functions that converts the
6283 // object parameter to a function pointer. Perform the conversion
6284 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006285
6286 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006287 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006288 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006289
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006290 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006291 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6292 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006293 }
6294
John McCall2cb94162010-01-28 07:38:46 +00006295 CheckMemberOperatorAccess(LParenLoc, Object,
6296 Best->Function, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006297
Douglas Gregorab7897a2008-11-19 22:57:39 +00006298 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6299 // that calls this method, using Object for the implicit object
6300 // parameter and passing along the remaining arguments.
6301 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006302 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006303
6304 unsigned NumArgsInProto = Proto->getNumArgs();
6305 unsigned NumArgsToCheck = NumArgs;
6306
6307 // Build the full argument list for the method call (the
6308 // implicit object parameter is placed at the beginning of the
6309 // list).
6310 Expr **MethodArgs;
6311 if (NumArgs < NumArgsInProto) {
6312 NumArgsToCheck = NumArgsInProto;
6313 MethodArgs = new Expr*[NumArgsInProto + 1];
6314 } else {
6315 MethodArgs = new Expr*[NumArgs + 1];
6316 }
6317 MethodArgs[0] = Object;
6318 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6319 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006320
6321 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006322 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006323 UsualUnaryConversions(NewFn);
6324
6325 // Once we've built TheCall, all of the expressions are properly
6326 // owned.
6327 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006328 ExprOwningPtr<CXXOperatorCallExpr>
6329 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006330 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006331 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006332 delete [] MethodArgs;
6333
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006334 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6335 Method))
6336 return true;
6337
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006338 // We may have default arguments. If so, we need to allocate more
6339 // slots in the call for them.
6340 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006341 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006342 else if (NumArgs > NumArgsInProto)
6343 NumArgsToCheck = NumArgsInProto;
6344
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006345 bool IsError = false;
6346
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006347 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006348 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006349 TheCall->setArg(0, Object);
6350
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006351
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006352 // Check the argument types.
6353 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006354 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006355 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006356 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006357
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006358 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006359
6360 OwningExprResult InputInit
6361 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6362 Method->getParamDecl(i)),
6363 SourceLocation(), Owned(Arg));
6364
6365 IsError |= InputInit.isInvalid();
6366 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006367 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006368 OwningExprResult DefArg
6369 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6370 if (DefArg.isInvalid()) {
6371 IsError = true;
6372 break;
6373 }
6374
6375 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006376 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006377
6378 TheCall->setArg(i + 1, Arg);
6379 }
6380
6381 // If this is a variadic call, handle args passed through "...".
6382 if (Proto->isVariadic()) {
6383 // Promote the arguments (C99 6.5.2.2p7).
6384 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6385 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006386 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006387 TheCall->setArg(i + 1, Arg);
6388 }
6389 }
6390
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006391 if (IsError) return true;
6392
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006393 if (CheckFunctionCall(Method, TheCall.get()))
6394 return true;
6395
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006396 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006397}
6398
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006399/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006400/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006401/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006402Sema::OwningExprResult
6403Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6404 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006405 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006406
John McCallbc077cf2010-02-08 23:07:23 +00006407 SourceLocation Loc = Base->getExprLoc();
6408
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006409 // C++ [over.ref]p1:
6410 //
6411 // [...] An expression x->m is interpreted as (x.operator->())->m
6412 // for a class object x of type T if T::operator->() exists and if
6413 // the operator is selected as the best match function by the
6414 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006415 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006416 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006417 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006418
John McCallbc077cf2010-02-08 23:07:23 +00006419 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006420 PDiag(diag::err_typecheck_incomplete_tag)
6421 << Base->getSourceRange()))
6422 return ExprError();
6423
John McCall27b18f82009-11-17 02:14:36 +00006424 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6425 LookupQualifiedName(R, BaseRecord->getDecl());
6426 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006427
6428 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006429 Oper != OperEnd; ++Oper) {
6430 NamedDecl *D = *Oper;
6431 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6432 if (isa<UsingShadowDecl>(D))
6433 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6434
John McCallb89836b2010-01-26 01:37:31 +00006435 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00006436 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006437 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006438 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006439
6440 // Perform overload resolution.
6441 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006442 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006443 case OR_Success:
6444 // Overload resolution succeeded; we'll build the call below.
6445 break;
6446
6447 case OR_No_Viable_Function:
6448 if (CandidateSet.empty())
6449 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006450 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006451 else
6452 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006453 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006454 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006455 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006456
6457 case OR_Ambiguous:
6458 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006459 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006460 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006461 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006462
6463 case OR_Deleted:
6464 Diag(OpLoc, diag::err_ovl_deleted_oper)
6465 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006466 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006467 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006468 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006469 }
6470
6471 // Convert the object parameter.
6472 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006473 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006474 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006475
6476 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006477 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006478
6479 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006480 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6481 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006482 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006483
6484 QualType ResultTy = Method->getResultType().getNonReferenceType();
6485 ExprOwningPtr<CXXOperatorCallExpr>
6486 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6487 &Base, 1, ResultTy, OpLoc));
6488
6489 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6490 Method))
6491 return ExprError();
6492 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006493}
6494
Douglas Gregorcd695e52008-11-10 20:40:00 +00006495/// FixOverloadedFunctionReference - E is an expression that refers to
6496/// a C++ overloaded function (possibly with some parentheses and
6497/// perhaps a '&' around it). We have resolved the overloaded function
6498/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006499/// refer (possibly indirectly) to Fn. Returns the new expr.
6500Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006501 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006502 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6503 if (SubExpr == PE->getSubExpr())
6504 return PE->Retain();
6505
6506 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6507 }
6508
6509 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6510 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006511 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006512 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006513 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006514 if (SubExpr == ICE->getSubExpr())
6515 return ICE->Retain();
6516
6517 return new (Context) ImplicitCastExpr(ICE->getType(),
6518 ICE->getCastKind(),
6519 SubExpr,
6520 ICE->isLvalueCast());
6521 }
6522
6523 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006524 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006525 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006526 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6527 if (Method->isStatic()) {
6528 // Do nothing: static member functions aren't any different
6529 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006530 } else {
John McCalle66edc12009-11-24 19:00:30 +00006531 // Fix the sub expression, which really has to be an
6532 // UnresolvedLookupExpr holding an overloaded member function
6533 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006534 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6535 if (SubExpr == UnOp->getSubExpr())
6536 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006537
John McCalld14a8642009-11-21 08:51:07 +00006538 assert(isa<DeclRefExpr>(SubExpr)
6539 && "fixed to something other than a decl ref");
6540 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6541 && "fixed to a member ref with no nested name qualifier");
6542
6543 // We have taken the address of a pointer to member
6544 // function. Perform the computation here so that we get the
6545 // appropriate pointer to member type.
6546 QualType ClassType
6547 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6548 QualType MemPtrType
6549 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6550
6551 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6552 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006553 }
6554 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006555 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6556 if (SubExpr == UnOp->getSubExpr())
6557 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006558
Douglas Gregor51c538b2009-11-20 19:42:02 +00006559 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6560 Context.getPointerType(SubExpr->getType()),
6561 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006562 }
John McCalld14a8642009-11-21 08:51:07 +00006563
6564 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006565 // FIXME: avoid copy.
6566 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006567 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006568 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6569 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006570 }
6571
John McCalld14a8642009-11-21 08:51:07 +00006572 return DeclRefExpr::Create(Context,
6573 ULE->getQualifier(),
6574 ULE->getQualifierRange(),
6575 Fn,
6576 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006577 Fn->getType(),
6578 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006579 }
6580
John McCall10eae182009-11-30 22:42:35 +00006581 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006582 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006583 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6584 if (MemExpr->hasExplicitTemplateArgs()) {
6585 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6586 TemplateArgs = &TemplateArgsBuffer;
6587 }
John McCall6b51f282009-11-23 01:53:49 +00006588
John McCall2d74de92009-12-01 22:10:20 +00006589 Expr *Base;
6590
6591 // If we're filling in
6592 if (MemExpr->isImplicitAccess()) {
6593 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6594 return DeclRefExpr::Create(Context,
6595 MemExpr->getQualifier(),
6596 MemExpr->getQualifierRange(),
6597 Fn,
6598 MemExpr->getMemberLoc(),
6599 Fn->getType(),
6600 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006601 } else {
6602 SourceLocation Loc = MemExpr->getMemberLoc();
6603 if (MemExpr->getQualifier())
6604 Loc = MemExpr->getQualifierRange().getBegin();
6605 Base = new (Context) CXXThisExpr(Loc,
6606 MemExpr->getBaseType(),
6607 /*isImplicit=*/true);
6608 }
John McCall2d74de92009-12-01 22:10:20 +00006609 } else
6610 Base = MemExpr->getBase()->Retain();
6611
6612 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006613 MemExpr->isArrow(),
6614 MemExpr->getQualifier(),
6615 MemExpr->getQualifierRange(),
6616 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006617 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006618 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006619 Fn->getType());
6620 }
6621
Douglas Gregor51c538b2009-11-20 19:42:02 +00006622 assert(false && "Invalid reference to overloaded function");
6623 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006624}
6625
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006626Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6627 FunctionDecl *Fn) {
6628 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6629}
6630
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006631} // end namespace clang