blob: 1c6fd17c381361a0b344aa7a4e1fc664d52c7bd9 [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() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002442 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2443 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002444 return;
2445 }
2446
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002447 // Add this candidate
2448 CandidateSet.push_back(OverloadCandidate());
2449 OverloadCandidate& Candidate = CandidateSet.back();
2450 Candidate.Function = Function;
John McCallb89836b2010-01-26 01:37:31 +00002451 Candidate.Access = Access;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002452 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002453 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002454 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002455
2456 unsigned NumArgsInProto = Proto->getNumArgs();
2457
2458 // (C++ 13.3.2p2): A candidate function having fewer than m
2459 // parameters is viable only if it has an ellipsis in its parameter
2460 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002461 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2462 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002463 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002464 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002465 return;
2466 }
2467
2468 // (C++ 13.3.2p2): A candidate function having more than m parameters
2469 // is viable only if the (m+1)st parameter has a default argument
2470 // (8.3.6). For the purposes of overload resolution, the
2471 // parameter list is truncated on the right, so that there are
2472 // exactly m parameters.
2473 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002474 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002475 // Not enough arguments.
2476 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002477 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002478 return;
2479 }
2480
2481 // Determine the implicit conversion sequences for each of the
2482 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002483 Candidate.Conversions.resize(NumArgs);
2484 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2485 if (ArgIdx < NumArgsInProto) {
2486 // (C++ 13.3.2p3): for F to be a viable function, there shall
2487 // exist for each argument an implicit conversion sequence
2488 // (13.3.3.1) that converts that argument to the corresponding
2489 // parameter of F.
2490 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002491 Candidate.Conversions[ArgIdx]
2492 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002493 SuppressUserConversions, ForceRValue,
2494 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002495 if (Candidate.Conversions[ArgIdx].isBad()) {
2496 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002497 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002498 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002499 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002500 } else {
2501 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2502 // argument for which there is no corresponding parameter is
2503 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002504 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002505 }
2506 }
2507}
2508
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002509/// \brief Add all of the function declarations in the given function set to
2510/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002511void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002512 Expr **Args, unsigned NumArgs,
2513 OverloadCandidateSet& CandidateSet,
2514 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002515 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002516 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002517 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2518 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002519 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002520 cast<CXXMethodDecl>(FD)->getParent(),
2521 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002522 CandidateSet, SuppressUserConversions);
2523 else
John McCallb89836b2010-01-26 01:37:31 +00002524 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002525 SuppressUserConversions);
2526 } else {
2527 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2528 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2529 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002530 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002531 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002532 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002533 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002534 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002535 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002536 else
John McCallb89836b2010-01-26 01:37:31 +00002537 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCall6b51f282009-11-23 01:53:49 +00002538 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002539 Args, NumArgs, CandidateSet,
2540 SuppressUserConversions);
2541 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002542 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002543}
2544
John McCallf0f1cf02009-11-17 07:50:12 +00002545/// AddMethodCandidate - Adds a named decl (which is some kind of
2546/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002547void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCallb89836b2010-01-26 01:37:31 +00002548 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002549 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002550 Expr **Args, unsigned NumArgs,
2551 OverloadCandidateSet& CandidateSet,
2552 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002553 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002554
2555 if (isa<UsingShadowDecl>(Decl))
2556 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2557
2558 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2559 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2560 "Expected a member function template");
John McCallb89836b2010-01-26 01:37:31 +00002561 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002562 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002563 CandidateSet,
2564 SuppressUserConversions,
2565 ForceRValue);
2566 } else {
John McCallb89836b2010-01-26 01:37:31 +00002567 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002568 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002569 CandidateSet, SuppressUserConversions, ForceRValue);
2570 }
2571}
2572
Douglas Gregor436424c2008-11-18 23:14:02 +00002573/// AddMethodCandidate - Adds the given C++ member function to the set
2574/// of candidate functions, using the given function call arguments
2575/// and the object argument (@c Object). For example, in a call
2576/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2577/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2578/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002579/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2580/// a slightly hacky way to implement the overloading rules for elidable copy
2581/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002582void
John McCallb89836b2010-01-26 01:37:31 +00002583Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2584 CXXRecordDecl *ActingContext, QualType ObjectType,
2585 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002586 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002587 bool SuppressUserConversions, bool ForceRValue) {
2588 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002589 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002590 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002591 assert(!isa<CXXConstructorDecl>(Method) &&
2592 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002593
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002594 if (!CandidateSet.isNewCandidate(Method))
2595 return;
2596
Douglas Gregor27381f32009-11-23 12:27:39 +00002597 // Overload resolution is always an unevaluated context.
2598 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2599
Douglas Gregor436424c2008-11-18 23:14:02 +00002600 // Add this candidate
2601 CandidateSet.push_back(OverloadCandidate());
2602 OverloadCandidate& Candidate = CandidateSet.back();
2603 Candidate.Function = Method;
John McCallb89836b2010-01-26 01:37:31 +00002604 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002605 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002606 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002607
2608 unsigned NumArgsInProto = Proto->getNumArgs();
2609
2610 // (C++ 13.3.2p2): A candidate function having fewer than m
2611 // parameters is viable only if it has an ellipsis in its parameter
2612 // list (8.3.5).
2613 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2614 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002615 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002616 return;
2617 }
2618
2619 // (C++ 13.3.2p2): A candidate function having more than m parameters
2620 // is viable only if the (m+1)st parameter has a default argument
2621 // (8.3.6). For the purposes of overload resolution, the
2622 // parameter list is truncated on the right, so that there are
2623 // exactly m parameters.
2624 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2625 if (NumArgs < MinRequiredArgs) {
2626 // Not enough arguments.
2627 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002628 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002629 return;
2630 }
2631
2632 Candidate.Viable = true;
2633 Candidate.Conversions.resize(NumArgs + 1);
2634
John McCall6e9f8f62009-12-03 04:06:58 +00002635 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002636 // The implicit object argument is ignored.
2637 Candidate.IgnoreObjectArgument = true;
2638 else {
2639 // Determine the implicit conversion sequence for the object
2640 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002641 Candidate.Conversions[0]
2642 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002643 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002644 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002645 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002646 return;
2647 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002648 }
2649
2650 // Determine the implicit conversion sequences for each of the
2651 // arguments.
2652 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2653 if (ArgIdx < NumArgsInProto) {
2654 // (C++ 13.3.2p3): for F to be a viable function, there shall
2655 // exist for each argument an implicit conversion sequence
2656 // (13.3.3.1) that converts that argument to the corresponding
2657 // parameter of F.
2658 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002659 Candidate.Conversions[ArgIdx + 1]
2660 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002661 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002662 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002663 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002664 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002665 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002666 break;
2667 }
2668 } else {
2669 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2670 // argument for which there is no corresponding parameter is
2671 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002672 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002673 }
2674 }
2675}
2676
Douglas Gregor97628d62009-08-21 00:16:32 +00002677/// \brief Add a C++ member function template as a candidate to the candidate
2678/// set, using template argument deduction to produce an appropriate member
2679/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002680void
Douglas Gregor97628d62009-08-21 00:16:32 +00002681Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCallb89836b2010-01-26 01:37:31 +00002682 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002683 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002684 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002685 QualType ObjectType,
2686 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002687 OverloadCandidateSet& CandidateSet,
2688 bool SuppressUserConversions,
2689 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002690 if (!CandidateSet.isNewCandidate(MethodTmpl))
2691 return;
2692
Douglas Gregor97628d62009-08-21 00:16:32 +00002693 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002694 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002695 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002696 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002697 // candidate functions in the usual way.113) A given name can refer to one
2698 // or more function templates and also to a set of overloaded non-template
2699 // functions. In such a case, the candidate functions generated from each
2700 // function template are combined with the set of non-template candidate
2701 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002702 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00002703 FunctionDecl *Specialization = 0;
2704 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002705 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002706 Args, NumArgs, Specialization, Info)) {
2707 // FIXME: Record what happened with template argument deduction, so
2708 // that we can give the user a beautiful diagnostic.
2709 (void)Result;
2710 return;
2711 }
Mike Stump11289f42009-09-09 15:08:12 +00002712
Douglas Gregor97628d62009-08-21 00:16:32 +00002713 // Add the function template specialization produced by template argument
2714 // deduction as a candidate.
2715 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002716 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002717 "Specialization is not a member function?");
John McCallb89836b2010-01-26 01:37:31 +00002718 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2719 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002720 CandidateSet, SuppressUserConversions, ForceRValue);
2721}
2722
Douglas Gregor05155d82009-08-21 23:19:43 +00002723/// \brief Add a C++ function template specialization as a candidate
2724/// in the candidate set, using template argument deduction to produce
2725/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002726void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002727Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002728 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00002729 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002730 Expr **Args, unsigned NumArgs,
2731 OverloadCandidateSet& CandidateSet,
2732 bool SuppressUserConversions,
2733 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002734 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2735 return;
2736
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002737 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002738 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002739 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002740 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002741 // candidate functions in the usual way.113) A given name can refer to one
2742 // or more function templates and also to a set of overloaded non-template
2743 // functions. In such a case, the candidate functions generated from each
2744 // function template are combined with the set of non-template candidate
2745 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002746 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002747 FunctionDecl *Specialization = 0;
2748 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002749 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002750 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00002751 CandidateSet.push_back(OverloadCandidate());
2752 OverloadCandidate &Candidate = CandidateSet.back();
2753 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCallb89836b2010-01-26 01:37:31 +00002754 Candidate.Access = Access;
John McCalld681c392009-12-16 08:11:27 +00002755 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002756 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002757 Candidate.IsSurrogate = false;
2758 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00002759
2760 // TODO: record more information about failed template arguments
2761 Candidate.DeductionFailure.Result = Result;
2762 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002763 return;
2764 }
Mike Stump11289f42009-09-09 15:08:12 +00002765
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002766 // Add the function template specialization produced by template argument
2767 // deduction as a candidate.
2768 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002769 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002770 SuppressUserConversions, ForceRValue);
2771}
Mike Stump11289f42009-09-09 15:08:12 +00002772
Douglas Gregora1f013e2008-11-07 22:36:19 +00002773/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002774/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002775/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002776/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002777/// (which may or may not be the same type as the type that the
2778/// conversion function produces).
2779void
2780Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002781 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002782 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002783 Expr *From, QualType ToType,
2784 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002785 assert(!Conversion->getDescribedFunctionTemplate() &&
2786 "Conversion function templates use AddTemplateConversionCandidate");
2787
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002788 if (!CandidateSet.isNewCandidate(Conversion))
2789 return;
2790
Douglas Gregor27381f32009-11-23 12:27:39 +00002791 // Overload resolution is always an unevaluated context.
2792 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2793
Douglas Gregora1f013e2008-11-07 22:36:19 +00002794 // Add this candidate
2795 CandidateSet.push_back(OverloadCandidate());
2796 OverloadCandidate& Candidate = CandidateSet.back();
2797 Candidate.Function = Conversion;
John McCallb89836b2010-01-26 01:37:31 +00002798 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002799 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002800 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002801 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002802 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002803 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002804
Douglas Gregor436424c2008-11-18 23:14:02 +00002805 // Determine the implicit conversion sequence for the implicit
2806 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002807 Candidate.Viable = true;
2808 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002809 Candidate.Conversions[0]
2810 = TryObjectArgumentInitialization(From->getType(), Conversion,
2811 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002812 // Conversion functions to a different type in the base class is visible in
2813 // the derived class. So, a derived to base conversion should not participate
2814 // in overload resolution.
2815 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2816 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002817 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002818 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002819 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002820 return;
2821 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002822
2823 // We won't go through a user-define type conversion function to convert a
2824 // derived to base as such conversions are given Conversion Rank. They only
2825 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2826 QualType FromCanon
2827 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2828 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2829 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2830 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002831 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002832 return;
2833 }
2834
Douglas Gregora1f013e2008-11-07 22:36:19 +00002835
2836 // To determine what the conversion from the result of calling the
2837 // conversion function to the type we're eventually trying to
2838 // convert to (ToType), we need to synthesize a call to the
2839 // conversion function and attempt copy initialization from it. This
2840 // makes sure that we get the right semantics with respect to
2841 // lvalues/rvalues and the type. Fortunately, we can allocate this
2842 // call on the stack and we don't need its arguments to be
2843 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002844 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002845 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002846 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002847 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002848 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002849
2850 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002851 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2852 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002853 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002854 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002855 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002856 ImplicitConversionSequence ICS =
2857 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002858 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002859 /*ForceRValue=*/false,
2860 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002861
John McCall0d1da222010-01-12 00:44:57 +00002862 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002863 case ImplicitConversionSequence::StandardConversion:
2864 Candidate.FinalConversion = ICS.Standard;
2865 break;
2866
2867 case ImplicitConversionSequence::BadConversion:
2868 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002869 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002870 break;
2871
2872 default:
Mike Stump11289f42009-09-09 15:08:12 +00002873 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002874 "Can only end up with a standard conversion sequence or failure");
2875 }
2876}
2877
Douglas Gregor05155d82009-08-21 23:19:43 +00002878/// \brief Adds a conversion function template specialization
2879/// candidate to the overload set, using template argument deduction
2880/// to deduce the template arguments of the conversion function
2881/// template from the type that we are converting to (C++
2882/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002883void
Douglas Gregor05155d82009-08-21 23:19:43 +00002884Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002885 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002886 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002887 Expr *From, QualType ToType,
2888 OverloadCandidateSet &CandidateSet) {
2889 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2890 "Only conversion function templates permitted here");
2891
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002892 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2893 return;
2894
John McCallbc077cf2010-02-08 23:07:23 +00002895 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00002896 CXXConversionDecl *Specialization = 0;
2897 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002898 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002899 Specialization, Info)) {
2900 // FIXME: Record what happened with template argument deduction, so
2901 // that we can give the user a beautiful diagnostic.
2902 (void)Result;
2903 return;
2904 }
Mike Stump11289f42009-09-09 15:08:12 +00002905
Douglas Gregor05155d82009-08-21 23:19:43 +00002906 // Add the conversion function template specialization produced by
2907 // template argument deduction as a candidate.
2908 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002909 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2910 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002911}
2912
Douglas Gregorab7897a2008-11-19 22:57:39 +00002913/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2914/// converts the given @c Object to a function pointer via the
2915/// conversion function @c Conversion, and then attempts to call it
2916/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2917/// the type of function that we'll eventually be calling.
2918void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002919 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002920 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002921 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002922 QualType ObjectType,
2923 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002924 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002925 if (!CandidateSet.isNewCandidate(Conversion))
2926 return;
2927
Douglas Gregor27381f32009-11-23 12:27:39 +00002928 // Overload resolution is always an unevaluated context.
2929 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2930
Douglas Gregorab7897a2008-11-19 22:57:39 +00002931 CandidateSet.push_back(OverloadCandidate());
2932 OverloadCandidate& Candidate = CandidateSet.back();
2933 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00002934 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002935 Candidate.Surrogate = Conversion;
2936 Candidate.Viable = true;
2937 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002938 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002939 Candidate.Conversions.resize(NumArgs + 1);
2940
2941 // Determine the implicit conversion sequence for the implicit
2942 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002943 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002944 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002945 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002946 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002947 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00002948 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002949 return;
2950 }
2951
2952 // The first conversion is actually a user-defined conversion whose
2953 // first conversion is ObjectInit's standard conversion (which is
2954 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002955 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002956 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002957 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002958 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002959 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002960 = Candidate.Conversions[0].UserDefined.Before;
2961 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2962
Mike Stump11289f42009-09-09 15:08:12 +00002963 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002964 unsigned NumArgsInProto = Proto->getNumArgs();
2965
2966 // (C++ 13.3.2p2): A candidate function having fewer than m
2967 // parameters is viable only if it has an ellipsis in its parameter
2968 // list (8.3.5).
2969 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2970 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002971 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002972 return;
2973 }
2974
2975 // Function types don't have any default arguments, so just check if
2976 // we have enough arguments.
2977 if (NumArgs < NumArgsInProto) {
2978 // Not enough arguments.
2979 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002980 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002981 return;
2982 }
2983
2984 // Determine the implicit conversion sequences for each of the
2985 // arguments.
2986 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2987 if (ArgIdx < NumArgsInProto) {
2988 // (C++ 13.3.2p3): for F to be a viable function, there shall
2989 // exist for each argument an implicit conversion sequence
2990 // (13.3.3.1) that converts that argument to the corresponding
2991 // parameter of F.
2992 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002993 Candidate.Conversions[ArgIdx + 1]
2994 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002995 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002996 /*ForceRValue=*/false,
2997 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002998 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002999 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003000 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003001 break;
3002 }
3003 } else {
3004 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3005 // argument for which there is no corresponding parameter is
3006 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003007 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003008 }
3009 }
3010}
3011
Mike Stump87c57ac2009-05-16 07:39:55 +00003012// FIXME: This will eventually be removed, once we've migrated all of the
3013// operator overloading logic over to the scheme used by binary operators, which
3014// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003015void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003016 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003017 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003018 OverloadCandidateSet& CandidateSet,
3019 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003020 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003021
3022 QualType T1 = Args[0]->getType();
3023 QualType T2;
3024 if (NumArgs > 1)
3025 T2 = Args[1]->getType();
3026
3027 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003028 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003029 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3030 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3031 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3032 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003033 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003034 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003035}
3036
3037/// \brief Add overload candidates for overloaded operators that are
3038/// member functions.
3039///
3040/// Add the overloaded operator candidates that are member functions
3041/// for the operator Op that was used in an operator expression such
3042/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3043/// CandidateSet will store the added overload candidates. (C++
3044/// [over.match.oper]).
3045void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3046 SourceLocation OpLoc,
3047 Expr **Args, unsigned NumArgs,
3048 OverloadCandidateSet& CandidateSet,
3049 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003050 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3051
3052 // C++ [over.match.oper]p3:
3053 // For a unary operator @ with an operand of a type whose
3054 // cv-unqualified version is T1, and for a binary operator @ with
3055 // a left operand of a type whose cv-unqualified version is T1 and
3056 // a right operand of a type whose cv-unqualified version is T2,
3057 // three sets of candidate functions, designated member
3058 // candidates, non-member candidates and built-in candidates, are
3059 // constructed as follows:
3060 QualType T1 = Args[0]->getType();
3061 QualType T2;
3062 if (NumArgs > 1)
3063 T2 = Args[1]->getType();
3064
3065 // -- If T1 is a class type, the set of member candidates is the
3066 // result of the qualified lookup of T1::operator@
3067 // (13.3.1.1.1); otherwise, the set of member candidates is
3068 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003069 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003070 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003071 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003072 return;
Mike Stump11289f42009-09-09 15:08:12 +00003073
John McCall27b18f82009-11-17 02:14:36 +00003074 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3075 LookupQualifiedName(Operators, T1Rec->getDecl());
3076 Operators.suppressDiagnostics();
3077
Mike Stump11289f42009-09-09 15:08:12 +00003078 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003079 OperEnd = Operators.end();
3080 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003081 ++Oper)
John McCallb89836b2010-01-26 01:37:31 +00003082 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003083 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003084 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003085 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003086}
3087
Douglas Gregora11693b2008-11-12 17:17:38 +00003088/// AddBuiltinCandidate - Add a candidate for a built-in
3089/// operator. ResultTy and ParamTys are the result and parameter types
3090/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003091/// arguments being passed to the candidate. IsAssignmentOperator
3092/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003093/// operator. NumContextualBoolArguments is the number of arguments
3094/// (at the beginning of the argument list) that will be contextually
3095/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003096void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003097 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003098 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003099 bool IsAssignmentOperator,
3100 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003101 // Overload resolution is always an unevaluated context.
3102 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3103
Douglas Gregora11693b2008-11-12 17:17:38 +00003104 // Add this candidate
3105 CandidateSet.push_back(OverloadCandidate());
3106 OverloadCandidate& Candidate = CandidateSet.back();
3107 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00003108 Candidate.Access = AS_none;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003109 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003110 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003111 Candidate.BuiltinTypes.ResultTy = ResultTy;
3112 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3113 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3114
3115 // Determine the implicit conversion sequences for each of the
3116 // arguments.
3117 Candidate.Viable = true;
3118 Candidate.Conversions.resize(NumArgs);
3119 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003120 // C++ [over.match.oper]p4:
3121 // For the built-in assignment operators, conversions of the
3122 // left operand are restricted as follows:
3123 // -- no temporaries are introduced to hold the left operand, and
3124 // -- no user-defined conversions are applied to the left
3125 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003126 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003127 //
3128 // We block these conversions by turning off user-defined
3129 // conversions, since that is the only way that initialization of
3130 // a reference to a non-class type can occur from something that
3131 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003132 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003133 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003134 "Contextual conversion to bool requires bool type");
3135 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3136 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003137 Candidate.Conversions[ArgIdx]
3138 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003139 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003140 /*ForceRValue=*/false,
3141 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003142 }
John McCall0d1da222010-01-12 00:44:57 +00003143 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003144 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003145 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003146 break;
3147 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003148 }
3149}
3150
3151/// BuiltinCandidateTypeSet - A set of types that will be used for the
3152/// candidate operator functions for built-in operators (C++
3153/// [over.built]). The types are separated into pointer types and
3154/// enumeration types.
3155class BuiltinCandidateTypeSet {
3156 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003157 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003158
3159 /// PointerTypes - The set of pointer types that will be used in the
3160 /// built-in candidates.
3161 TypeSet PointerTypes;
3162
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003163 /// MemberPointerTypes - The set of member pointer types that will be
3164 /// used in the built-in candidates.
3165 TypeSet MemberPointerTypes;
3166
Douglas Gregora11693b2008-11-12 17:17:38 +00003167 /// EnumerationTypes - The set of enumeration types that will be
3168 /// used in the built-in candidates.
3169 TypeSet EnumerationTypes;
3170
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003171 /// Sema - The semantic analysis instance where we are building the
3172 /// candidate type set.
3173 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003174
Douglas Gregora11693b2008-11-12 17:17:38 +00003175 /// Context - The AST context in which we will build the type sets.
3176 ASTContext &Context;
3177
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003178 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3179 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003180 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003181
3182public:
3183 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003184 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003185
Mike Stump11289f42009-09-09 15:08:12 +00003186 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003187 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003188
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003189 void AddTypesConvertedFrom(QualType Ty,
3190 SourceLocation Loc,
3191 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003192 bool AllowExplicitConversions,
3193 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003194
3195 /// pointer_begin - First pointer type found;
3196 iterator pointer_begin() { return PointerTypes.begin(); }
3197
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003198 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003199 iterator pointer_end() { return PointerTypes.end(); }
3200
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003201 /// member_pointer_begin - First member pointer type found;
3202 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3203
3204 /// member_pointer_end - Past the last member pointer type found;
3205 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3206
Douglas Gregora11693b2008-11-12 17:17:38 +00003207 /// enumeration_begin - First enumeration type found;
3208 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3209
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003210 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003211 iterator enumeration_end() { return EnumerationTypes.end(); }
3212};
3213
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003214/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003215/// the set of pointer types along with any more-qualified variants of
3216/// that type. For example, if @p Ty is "int const *", this routine
3217/// will add "int const *", "int const volatile *", "int const
3218/// restrict *", and "int const volatile restrict *" to the set of
3219/// pointer types. Returns true if the add of @p Ty itself succeeded,
3220/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003221///
3222/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003223bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003224BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3225 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003226
Douglas Gregora11693b2008-11-12 17:17:38 +00003227 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003228 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003229 return false;
3230
John McCall8ccfcb52009-09-24 19:53:00 +00003231 const PointerType *PointerTy = Ty->getAs<PointerType>();
3232 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003233
John McCall8ccfcb52009-09-24 19:53:00 +00003234 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003235 // Don't add qualified variants of arrays. For one, they're not allowed
3236 // (the qualifier would sink to the element type), and for another, the
3237 // only overload situation where it matters is subscript or pointer +- int,
3238 // and those shouldn't have qualifier variants anyway.
3239 if (PointeeTy->isArrayType())
3240 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003241 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003242 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003243 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003244 bool hasVolatile = VisibleQuals.hasVolatile();
3245 bool hasRestrict = VisibleQuals.hasRestrict();
3246
John McCall8ccfcb52009-09-24 19:53:00 +00003247 // Iterate through all strict supersets of BaseCVR.
3248 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3249 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003250 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3251 // in the types.
3252 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3253 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003254 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3255 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003256 }
3257
3258 return true;
3259}
3260
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003261/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3262/// to the set of pointer types along with any more-qualified variants of
3263/// that type. For example, if @p Ty is "int const *", this routine
3264/// will add "int const *", "int const volatile *", "int const
3265/// restrict *", and "int const volatile restrict *" to the set of
3266/// pointer types. Returns true if the add of @p Ty itself succeeded,
3267/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003268///
3269/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003270bool
3271BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3272 QualType Ty) {
3273 // Insert this type.
3274 if (!MemberPointerTypes.insert(Ty))
3275 return false;
3276
John McCall8ccfcb52009-09-24 19:53:00 +00003277 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3278 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003279
John McCall8ccfcb52009-09-24 19:53:00 +00003280 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003281 // Don't add qualified variants of arrays. For one, they're not allowed
3282 // (the qualifier would sink to the element type), and for another, the
3283 // only overload situation where it matters is subscript or pointer +- int,
3284 // and those shouldn't have qualifier variants anyway.
3285 if (PointeeTy->isArrayType())
3286 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003287 const Type *ClassTy = PointerTy->getClass();
3288
3289 // Iterate through all strict supersets of the pointee type's CVR
3290 // qualifiers.
3291 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3292 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3293 if ((CVR | BaseCVR) != CVR) continue;
3294
3295 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3296 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003297 }
3298
3299 return true;
3300}
3301
Douglas Gregora11693b2008-11-12 17:17:38 +00003302/// AddTypesConvertedFrom - Add each of the types to which the type @p
3303/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003304/// primarily interested in pointer types and enumeration types. We also
3305/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003306/// AllowUserConversions is true if we should look at the conversion
3307/// functions of a class type, and AllowExplicitConversions if we
3308/// should also include the explicit conversion functions of a class
3309/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003310void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003311BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003312 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003313 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003314 bool AllowExplicitConversions,
3315 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003316 // Only deal with canonical types.
3317 Ty = Context.getCanonicalType(Ty);
3318
3319 // Look through reference types; they aren't part of the type of an
3320 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003321 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003322 Ty = RefTy->getPointeeType();
3323
3324 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003325 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003326
Sebastian Redl65ae2002009-11-05 16:36:20 +00003327 // If we're dealing with an array type, decay to the pointer.
3328 if (Ty->isArrayType())
3329 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3330
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003331 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003332 QualType PointeeTy = PointerTy->getPointeeType();
3333
3334 // Insert our type, and its more-qualified variants, into the set
3335 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003336 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003337 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003338 } else if (Ty->isMemberPointerType()) {
3339 // Member pointers are far easier, since the pointee can't be converted.
3340 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3341 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003342 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003343 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003344 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003345 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003346 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003347 // No conversion functions in incomplete types.
3348 return;
3349 }
Mike Stump11289f42009-09-09 15:08:12 +00003350
Douglas Gregora11693b2008-11-12 17:17:38 +00003351 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003352 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003353 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003354 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003355 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003356
Mike Stump11289f42009-09-09 15:08:12 +00003357 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003358 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003359 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003360 continue;
3361
John McCalld14a8642009-11-21 08:51:07 +00003362 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003363 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003364 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003365 VisibleQuals);
3366 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003367 }
3368 }
3369 }
3370}
3371
Douglas Gregor84605ae2009-08-24 13:43:27 +00003372/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3373/// the volatile- and non-volatile-qualified assignment operators for the
3374/// given type to the candidate set.
3375static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3376 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003377 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003378 unsigned NumArgs,
3379 OverloadCandidateSet &CandidateSet) {
3380 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003381
Douglas Gregor84605ae2009-08-24 13:43:27 +00003382 // T& operator=(T&, T)
3383 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3384 ParamTypes[1] = T;
3385 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3386 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003387
Douglas Gregor84605ae2009-08-24 13:43:27 +00003388 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3389 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003390 ParamTypes[0]
3391 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003392 ParamTypes[1] = T;
3393 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003394 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003395 }
3396}
Mike Stump11289f42009-09-09 15:08:12 +00003397
Sebastian Redl1054fae2009-10-25 17:03:50 +00003398/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3399/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003400static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3401 Qualifiers VRQuals;
3402 const RecordType *TyRec;
3403 if (const MemberPointerType *RHSMPType =
3404 ArgExpr->getType()->getAs<MemberPointerType>())
3405 TyRec = cast<RecordType>(RHSMPType->getClass());
3406 else
3407 TyRec = ArgExpr->getType()->getAs<RecordType>();
3408 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003409 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003410 VRQuals.addVolatile();
3411 VRQuals.addRestrict();
3412 return VRQuals;
3413 }
3414
3415 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003416 if (!ClassDecl->hasDefinition())
3417 return VRQuals;
3418
John McCallad371252010-01-20 00:46:10 +00003419 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003420 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003421
John McCallad371252010-01-20 00:46:10 +00003422 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003423 E = Conversions->end(); I != E; ++I) {
3424 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003425 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3426 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3427 CanTy = ResTypeRef->getPointeeType();
3428 // Need to go down the pointer/mempointer chain and add qualifiers
3429 // as see them.
3430 bool done = false;
3431 while (!done) {
3432 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3433 CanTy = ResTypePtr->getPointeeType();
3434 else if (const MemberPointerType *ResTypeMPtr =
3435 CanTy->getAs<MemberPointerType>())
3436 CanTy = ResTypeMPtr->getPointeeType();
3437 else
3438 done = true;
3439 if (CanTy.isVolatileQualified())
3440 VRQuals.addVolatile();
3441 if (CanTy.isRestrictQualified())
3442 VRQuals.addRestrict();
3443 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3444 return VRQuals;
3445 }
3446 }
3447 }
3448 return VRQuals;
3449}
3450
Douglas Gregord08452f2008-11-19 15:42:04 +00003451/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3452/// operator overloads to the candidate set (C++ [over.built]), based
3453/// on the operator @p Op and the arguments given. For example, if the
3454/// operator is a binary '+', this routine might add "int
3455/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003456void
Mike Stump11289f42009-09-09 15:08:12 +00003457Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003458 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003459 Expr **Args, unsigned NumArgs,
3460 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003461 // The set of "promoted arithmetic types", which are the arithmetic
3462 // types are that preserved by promotion (C++ [over.built]p2). Note
3463 // that the first few of these types are the promoted integral
3464 // types; these types need to be first.
3465 // FIXME: What about complex?
3466 const unsigned FirstIntegralType = 0;
3467 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003468 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003469 LastPromotedIntegralType = 13;
3470 const unsigned FirstPromotedArithmeticType = 7,
3471 LastPromotedArithmeticType = 16;
3472 const unsigned NumArithmeticTypes = 16;
3473 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003474 Context.BoolTy, Context.CharTy, Context.WCharTy,
3475// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003476 Context.SignedCharTy, Context.ShortTy,
3477 Context.UnsignedCharTy, Context.UnsignedShortTy,
3478 Context.IntTy, Context.LongTy, Context.LongLongTy,
3479 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3480 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3481 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003482 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3483 "Invalid first promoted integral type");
3484 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3485 == Context.UnsignedLongLongTy &&
3486 "Invalid last promoted integral type");
3487 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3488 "Invalid first promoted arithmetic type");
3489 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3490 == Context.LongDoubleTy &&
3491 "Invalid last promoted arithmetic type");
3492
Douglas Gregora11693b2008-11-12 17:17:38 +00003493 // Find all of the types that the arguments can convert to, but only
3494 // if the operator we're looking at has built-in operator candidates
3495 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003496 Qualifiers VisibleTypeConversionsQuals;
3497 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003498 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3499 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3500
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003501 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003502 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3503 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003504 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003505 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003506 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003507 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003508 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003509 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003510 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003511 true,
3512 (Op == OO_Exclaim ||
3513 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003514 Op == OO_PipePipe),
3515 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003516 }
3517
3518 bool isComparison = false;
3519 switch (Op) {
3520 case OO_None:
3521 case NUM_OVERLOADED_OPERATORS:
3522 assert(false && "Expected an overloaded operator");
3523 break;
3524
Douglas Gregord08452f2008-11-19 15:42:04 +00003525 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003526 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003527 goto UnaryStar;
3528 else
3529 goto BinaryStar;
3530 break;
3531
3532 case OO_Plus: // '+' is either unary or binary
3533 if (NumArgs == 1)
3534 goto UnaryPlus;
3535 else
3536 goto BinaryPlus;
3537 break;
3538
3539 case OO_Minus: // '-' is either unary or binary
3540 if (NumArgs == 1)
3541 goto UnaryMinus;
3542 else
3543 goto BinaryMinus;
3544 break;
3545
3546 case OO_Amp: // '&' is either unary or binary
3547 if (NumArgs == 1)
3548 goto UnaryAmp;
3549 else
3550 goto BinaryAmp;
3551
3552 case OO_PlusPlus:
3553 case OO_MinusMinus:
3554 // C++ [over.built]p3:
3555 //
3556 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3557 // is either volatile or empty, there exist candidate operator
3558 // functions of the form
3559 //
3560 // VQ T& operator++(VQ T&);
3561 // T operator++(VQ T&, int);
3562 //
3563 // C++ [over.built]p4:
3564 //
3565 // For every pair (T, VQ), where T is an arithmetic type other
3566 // than bool, and VQ is either volatile or empty, there exist
3567 // candidate operator functions of the form
3568 //
3569 // VQ T& operator--(VQ T&);
3570 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003571 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003572 Arith < NumArithmeticTypes; ++Arith) {
3573 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003574 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003575 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003576
3577 // Non-volatile version.
3578 if (NumArgs == 1)
3579 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3580 else
3581 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003582 // heuristic to reduce number of builtin candidates in the set.
3583 // Add volatile version only if there are conversions to a volatile type.
3584 if (VisibleTypeConversionsQuals.hasVolatile()) {
3585 // Volatile version
3586 ParamTypes[0]
3587 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3588 if (NumArgs == 1)
3589 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3590 else
3591 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3592 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003593 }
3594
3595 // C++ [over.built]p5:
3596 //
3597 // For every pair (T, VQ), where T is a cv-qualified or
3598 // cv-unqualified object type, and VQ is either volatile or
3599 // empty, there exist candidate operator functions of the form
3600 //
3601 // T*VQ& operator++(T*VQ&);
3602 // T*VQ& operator--(T*VQ&);
3603 // T* operator++(T*VQ&, int);
3604 // T* operator--(T*VQ&, int);
3605 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3606 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3607 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003608 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003609 continue;
3610
Mike Stump11289f42009-09-09 15:08:12 +00003611 QualType ParamTypes[2] = {
3612 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003613 };
Mike Stump11289f42009-09-09 15:08:12 +00003614
Douglas Gregord08452f2008-11-19 15:42:04 +00003615 // Without volatile
3616 if (NumArgs == 1)
3617 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3618 else
3619 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3620
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003621 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3622 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003623 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003624 ParamTypes[0]
3625 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003626 if (NumArgs == 1)
3627 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3628 else
3629 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3630 }
3631 }
3632 break;
3633
3634 UnaryStar:
3635 // C++ [over.built]p6:
3636 // For every cv-qualified or cv-unqualified object type T, there
3637 // exist candidate operator functions of the form
3638 //
3639 // T& operator*(T*);
3640 //
3641 // C++ [over.built]p7:
3642 // For every function type T, there exist candidate operator
3643 // functions of the form
3644 // T& operator*(T*);
3645 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3646 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3647 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003648 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003649 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003650 &ParamTy, Args, 1, CandidateSet);
3651 }
3652 break;
3653
3654 UnaryPlus:
3655 // C++ [over.built]p8:
3656 // For every type T, there exist candidate operator functions of
3657 // the form
3658 //
3659 // T* operator+(T*);
3660 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3661 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3662 QualType ParamTy = *Ptr;
3663 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3664 }
Mike Stump11289f42009-09-09 15:08:12 +00003665
Douglas Gregord08452f2008-11-19 15:42:04 +00003666 // Fall through
3667
3668 UnaryMinus:
3669 // C++ [over.built]p9:
3670 // For every promoted arithmetic type T, there exist candidate
3671 // operator functions of the form
3672 //
3673 // T operator+(T);
3674 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003675 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003676 Arith < LastPromotedArithmeticType; ++Arith) {
3677 QualType ArithTy = ArithmeticTypes[Arith];
3678 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3679 }
3680 break;
3681
3682 case OO_Tilde:
3683 // C++ [over.built]p10:
3684 // For every promoted integral type T, there exist candidate
3685 // operator functions of the form
3686 //
3687 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003688 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003689 Int < LastPromotedIntegralType; ++Int) {
3690 QualType IntTy = ArithmeticTypes[Int];
3691 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3692 }
3693 break;
3694
Douglas Gregora11693b2008-11-12 17:17:38 +00003695 case OO_New:
3696 case OO_Delete:
3697 case OO_Array_New:
3698 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003699 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003700 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003701 break;
3702
3703 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003704 UnaryAmp:
3705 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003706 // C++ [over.match.oper]p3:
3707 // -- For the operator ',', the unary operator '&', or the
3708 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003709 break;
3710
Douglas Gregor84605ae2009-08-24 13:43:27 +00003711 case OO_EqualEqual:
3712 case OO_ExclaimEqual:
3713 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003714 // For every pointer to member type T, there exist candidate operator
3715 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003716 //
3717 // bool operator==(T,T);
3718 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003719 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003720 MemPtr = CandidateTypes.member_pointer_begin(),
3721 MemPtrEnd = CandidateTypes.member_pointer_end();
3722 MemPtr != MemPtrEnd;
3723 ++MemPtr) {
3724 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3725 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3726 }
Mike Stump11289f42009-09-09 15:08:12 +00003727
Douglas Gregor84605ae2009-08-24 13:43:27 +00003728 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003729
Douglas Gregora11693b2008-11-12 17:17:38 +00003730 case OO_Less:
3731 case OO_Greater:
3732 case OO_LessEqual:
3733 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003734 // C++ [over.built]p15:
3735 //
3736 // For every pointer or enumeration type T, there exist
3737 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003738 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003739 // bool operator<(T, T);
3740 // bool operator>(T, T);
3741 // bool operator<=(T, T);
3742 // bool operator>=(T, T);
3743 // bool operator==(T, T);
3744 // bool operator!=(T, T);
3745 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3746 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3747 QualType ParamTypes[2] = { *Ptr, *Ptr };
3748 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3749 }
Mike Stump11289f42009-09-09 15:08:12 +00003750 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003751 = CandidateTypes.enumeration_begin();
3752 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3753 QualType ParamTypes[2] = { *Enum, *Enum };
3754 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3755 }
3756
3757 // Fall through.
3758 isComparison = true;
3759
Douglas Gregord08452f2008-11-19 15:42:04 +00003760 BinaryPlus:
3761 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003762 if (!isComparison) {
3763 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3764
3765 // C++ [over.built]p13:
3766 //
3767 // For every cv-qualified or cv-unqualified object type T
3768 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003769 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003770 // T* operator+(T*, ptrdiff_t);
3771 // T& operator[](T*, ptrdiff_t); [BELOW]
3772 // T* operator-(T*, ptrdiff_t);
3773 // T* operator+(ptrdiff_t, T*);
3774 // T& operator[](ptrdiff_t, T*); [BELOW]
3775 //
3776 // C++ [over.built]p14:
3777 //
3778 // For every T, where T is a pointer to object type, there
3779 // exist candidate operator functions of the form
3780 //
3781 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003782 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003783 = CandidateTypes.pointer_begin();
3784 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3785 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3786
3787 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3788 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3789
3790 if (Op == OO_Plus) {
3791 // T* operator+(ptrdiff_t, T*);
3792 ParamTypes[0] = ParamTypes[1];
3793 ParamTypes[1] = *Ptr;
3794 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3795 } else {
3796 // ptrdiff_t operator-(T, T);
3797 ParamTypes[1] = *Ptr;
3798 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3799 Args, 2, CandidateSet);
3800 }
3801 }
3802 }
3803 // Fall through
3804
Douglas Gregora11693b2008-11-12 17:17:38 +00003805 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003806 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003807 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003808 // C++ [over.built]p12:
3809 //
3810 // For every pair of promoted arithmetic types L and R, there
3811 // exist candidate operator functions of the form
3812 //
3813 // LR operator*(L, R);
3814 // LR operator/(L, R);
3815 // LR operator+(L, R);
3816 // LR operator-(L, R);
3817 // bool operator<(L, R);
3818 // bool operator>(L, R);
3819 // bool operator<=(L, R);
3820 // bool operator>=(L, R);
3821 // bool operator==(L, R);
3822 // bool operator!=(L, R);
3823 //
3824 // where LR is the result of the usual arithmetic conversions
3825 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003826 //
3827 // C++ [over.built]p24:
3828 //
3829 // For every pair of promoted arithmetic types L and R, there exist
3830 // candidate operator functions of the form
3831 //
3832 // LR operator?(bool, L, R);
3833 //
3834 // where LR is the result of the usual arithmetic conversions
3835 // between types L and R.
3836 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003837 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003838 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003839 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003840 Right < LastPromotedArithmeticType; ++Right) {
3841 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003842 QualType Result
3843 = isComparison
3844 ? Context.BoolTy
3845 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003846 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3847 }
3848 }
3849 break;
3850
3851 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003852 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003853 case OO_Caret:
3854 case OO_Pipe:
3855 case OO_LessLess:
3856 case OO_GreaterGreater:
3857 // C++ [over.built]p17:
3858 //
3859 // For every pair of promoted integral types L and R, there
3860 // exist candidate operator functions of the form
3861 //
3862 // LR operator%(L, R);
3863 // LR operator&(L, R);
3864 // LR operator^(L, R);
3865 // LR operator|(L, R);
3866 // L operator<<(L, R);
3867 // L operator>>(L, R);
3868 //
3869 // where LR is the result of the usual arithmetic conversions
3870 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003871 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003872 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003873 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003874 Right < LastPromotedIntegralType; ++Right) {
3875 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3876 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3877 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003878 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003879 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3880 }
3881 }
3882 break;
3883
3884 case OO_Equal:
3885 // C++ [over.built]p20:
3886 //
3887 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003888 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003889 // empty, there exist candidate operator functions of the form
3890 //
3891 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003892 for (BuiltinCandidateTypeSet::iterator
3893 Enum = CandidateTypes.enumeration_begin(),
3894 EnumEnd = CandidateTypes.enumeration_end();
3895 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003896 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003897 CandidateSet);
3898 for (BuiltinCandidateTypeSet::iterator
3899 MemPtr = CandidateTypes.member_pointer_begin(),
3900 MemPtrEnd = CandidateTypes.member_pointer_end();
3901 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003902 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003903 CandidateSet);
3904 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003905
3906 case OO_PlusEqual:
3907 case OO_MinusEqual:
3908 // C++ [over.built]p19:
3909 //
3910 // For every pair (T, VQ), where T is any type and VQ is either
3911 // volatile or empty, there exist candidate operator functions
3912 // of the form
3913 //
3914 // T*VQ& operator=(T*VQ&, T*);
3915 //
3916 // C++ [over.built]p21:
3917 //
3918 // For every pair (T, VQ), where T is a cv-qualified or
3919 // cv-unqualified object type and VQ is either volatile or
3920 // empty, there exist candidate operator functions of the form
3921 //
3922 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3923 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3924 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3925 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3926 QualType ParamTypes[2];
3927 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3928
3929 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003930 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3932 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003933
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003934 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3935 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003936 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003937 ParamTypes[0]
3938 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003939 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3940 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003941 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003942 }
3943 // Fall through.
3944
3945 case OO_StarEqual:
3946 case OO_SlashEqual:
3947 // C++ [over.built]p18:
3948 //
3949 // For every triple (L, VQ, R), where L is an arithmetic type,
3950 // VQ is either volatile or empty, and R is a promoted
3951 // arithmetic type, there exist candidate operator functions of
3952 // the form
3953 //
3954 // VQ L& operator=(VQ L&, R);
3955 // VQ L& operator*=(VQ L&, R);
3956 // VQ L& operator/=(VQ L&, R);
3957 // VQ L& operator+=(VQ L&, R);
3958 // VQ L& operator-=(VQ L&, R);
3959 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003960 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003961 Right < LastPromotedArithmeticType; ++Right) {
3962 QualType ParamTypes[2];
3963 ParamTypes[1] = ArithmeticTypes[Right];
3964
3965 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003966 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003967 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3968 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003969
3970 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003971 if (VisibleTypeConversionsQuals.hasVolatile()) {
3972 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3973 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3974 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3975 /*IsAssigmentOperator=*/Op == OO_Equal);
3976 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003977 }
3978 }
3979 break;
3980
3981 case OO_PercentEqual:
3982 case OO_LessLessEqual:
3983 case OO_GreaterGreaterEqual:
3984 case OO_AmpEqual:
3985 case OO_CaretEqual:
3986 case OO_PipeEqual:
3987 // C++ [over.built]p22:
3988 //
3989 // For every triple (L, VQ, R), where L is an integral type, VQ
3990 // is either volatile or empty, and R is a promoted integral
3991 // type, there exist candidate operator functions of the form
3992 //
3993 // VQ L& operator%=(VQ L&, R);
3994 // VQ L& operator<<=(VQ L&, R);
3995 // VQ L& operator>>=(VQ L&, R);
3996 // VQ L& operator&=(VQ L&, R);
3997 // VQ L& operator^=(VQ L&, R);
3998 // VQ L& operator|=(VQ L&, R);
3999 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004000 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004001 Right < LastPromotedIntegralType; ++Right) {
4002 QualType ParamTypes[2];
4003 ParamTypes[1] = ArithmeticTypes[Right];
4004
4005 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004006 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004007 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004008 if (VisibleTypeConversionsQuals.hasVolatile()) {
4009 // Add this built-in operator as a candidate (VQ is 'volatile').
4010 ParamTypes[0] = ArithmeticTypes[Left];
4011 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4012 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4013 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4014 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004015 }
4016 }
4017 break;
4018
Douglas Gregord08452f2008-11-19 15:42:04 +00004019 case OO_Exclaim: {
4020 // C++ [over.operator]p23:
4021 //
4022 // There also exist candidate operator functions of the form
4023 //
Mike Stump11289f42009-09-09 15:08:12 +00004024 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004025 // bool operator&&(bool, bool); [BELOW]
4026 // bool operator||(bool, bool); [BELOW]
4027 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004028 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4029 /*IsAssignmentOperator=*/false,
4030 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004031 break;
4032 }
4033
Douglas Gregora11693b2008-11-12 17:17:38 +00004034 case OO_AmpAmp:
4035 case OO_PipePipe: {
4036 // C++ [over.operator]p23:
4037 //
4038 // There also exist candidate operator functions of the form
4039 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004040 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004041 // bool operator&&(bool, bool);
4042 // bool operator||(bool, bool);
4043 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004044 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4045 /*IsAssignmentOperator=*/false,
4046 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004047 break;
4048 }
4049
4050 case OO_Subscript:
4051 // C++ [over.built]p13:
4052 //
4053 // For every cv-qualified or cv-unqualified object type T there
4054 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004055 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004056 // T* operator+(T*, ptrdiff_t); [ABOVE]
4057 // T& operator[](T*, ptrdiff_t);
4058 // T* operator-(T*, ptrdiff_t); [ABOVE]
4059 // T* operator+(ptrdiff_t, T*); [ABOVE]
4060 // T& operator[](ptrdiff_t, T*);
4061 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4062 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4063 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004064 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004065 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004066
4067 // T& operator[](T*, ptrdiff_t)
4068 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4069
4070 // T& operator[](ptrdiff_t, T*);
4071 ParamTypes[0] = ParamTypes[1];
4072 ParamTypes[1] = *Ptr;
4073 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4074 }
4075 break;
4076
4077 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004078 // C++ [over.built]p11:
4079 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4080 // C1 is the same type as C2 or is a derived class of C2, T is an object
4081 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4082 // there exist candidate operator functions of the form
4083 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4084 // where CV12 is the union of CV1 and CV2.
4085 {
4086 for (BuiltinCandidateTypeSet::iterator Ptr =
4087 CandidateTypes.pointer_begin();
4088 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4089 QualType C1Ty = (*Ptr);
4090 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004091 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004092 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004093 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004094 if (!isa<RecordType>(C1))
4095 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004096 // heuristic to reduce number of builtin candidates in the set.
4097 // Add volatile/restrict version only if there are conversions to a
4098 // volatile/restrict type.
4099 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4100 continue;
4101 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4102 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004103 }
4104 for (BuiltinCandidateTypeSet::iterator
4105 MemPtr = CandidateTypes.member_pointer_begin(),
4106 MemPtrEnd = CandidateTypes.member_pointer_end();
4107 MemPtr != MemPtrEnd; ++MemPtr) {
4108 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4109 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004110 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004111 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4112 break;
4113 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4114 // build CV12 T&
4115 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004116 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4117 T.isVolatileQualified())
4118 continue;
4119 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4120 T.isRestrictQualified())
4121 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004122 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004123 QualType ResultTy = Context.getLValueReferenceType(T);
4124 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4125 }
4126 }
4127 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004128 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004129
4130 case OO_Conditional:
4131 // Note that we don't consider the first argument, since it has been
4132 // contextually converted to bool long ago. The candidates below are
4133 // therefore added as binary.
4134 //
4135 // C++ [over.built]p24:
4136 // For every type T, where T is a pointer or pointer-to-member type,
4137 // there exist candidate operator functions of the form
4138 //
4139 // T operator?(bool, T, T);
4140 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004141 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4142 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4143 QualType ParamTypes[2] = { *Ptr, *Ptr };
4144 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4145 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004146 for (BuiltinCandidateTypeSet::iterator Ptr =
4147 CandidateTypes.member_pointer_begin(),
4148 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4149 QualType ParamTypes[2] = { *Ptr, *Ptr };
4150 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4151 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004152 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004153 }
4154}
4155
Douglas Gregore254f902009-02-04 00:32:51 +00004156/// \brief Add function candidates found via argument-dependent lookup
4157/// to the set of overloading candidates.
4158///
4159/// This routine performs argument-dependent name lookup based on the
4160/// given function name (which may also be an operator name) and adds
4161/// all of the overload candidates found by ADL to the overload
4162/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004163void
Douglas Gregore254f902009-02-04 00:32:51 +00004164Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004165 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004166 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004167 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004168 OverloadCandidateSet& CandidateSet,
4169 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004170 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004171
John McCall91f61fc2010-01-26 06:04:06 +00004172 // FIXME: This approach for uniquing ADL results (and removing
4173 // redundant candidates from the set) relies on pointer-equality,
4174 // which means we need to key off the canonical decl. However,
4175 // always going back to the canonical decl might not get us the
4176 // right set of default arguments. What default arguments are
4177 // we supposed to consider on ADL candidates, anyway?
4178
Douglas Gregorcabea402009-09-22 15:41:20 +00004179 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004180 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004181
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004182 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004183 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4184 CandEnd = CandidateSet.end();
4185 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004186 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004187 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004188 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004189 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004190 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004191
4192 // For each of the ADL candidates we found, add it to the overload
4193 // set.
John McCall8fe68082010-01-26 07:16:45 +00004194 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00004195 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004196 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004197 continue;
4198
John McCallb89836b2010-01-26 01:37:31 +00004199 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004200 false, false, PartialOverloading);
4201 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004202 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCallb89836b2010-01-26 01:37:31 +00004203 AS_none, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004204 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004205 }
Douglas Gregore254f902009-02-04 00:32:51 +00004206}
4207
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004208/// isBetterOverloadCandidate - Determines whether the first overload
4209/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004210bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004211Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004212 const OverloadCandidate& Cand2,
4213 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004214 // Define viable functions to be better candidates than non-viable
4215 // functions.
4216 if (!Cand2.Viable)
4217 return Cand1.Viable;
4218 else if (!Cand1.Viable)
4219 return false;
4220
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004221 // C++ [over.match.best]p1:
4222 //
4223 // -- if F is a static member function, ICS1(F) is defined such
4224 // that ICS1(F) is neither better nor worse than ICS1(G) for
4225 // any function G, and, symmetrically, ICS1(G) is neither
4226 // better nor worse than ICS1(F).
4227 unsigned StartArg = 0;
4228 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4229 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004230
Douglas Gregord3cb3562009-07-07 23:38:56 +00004231 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004232 // A viable function F1 is defined to be a better function than another
4233 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004234 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004235 unsigned NumArgs = Cand1.Conversions.size();
4236 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4237 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004238 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004239 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4240 Cand2.Conversions[ArgIdx])) {
4241 case ImplicitConversionSequence::Better:
4242 // Cand1 has a better conversion sequence.
4243 HasBetterConversion = true;
4244 break;
4245
4246 case ImplicitConversionSequence::Worse:
4247 // Cand1 can't be better than Cand2.
4248 return false;
4249
4250 case ImplicitConversionSequence::Indistinguishable:
4251 // Do nothing.
4252 break;
4253 }
4254 }
4255
Mike Stump11289f42009-09-09 15:08:12 +00004256 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004257 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004258 if (HasBetterConversion)
4259 return true;
4260
Mike Stump11289f42009-09-09 15:08:12 +00004261 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004262 // specialization, or, if not that,
4263 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4264 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4265 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004266
4267 // -- F1 and F2 are function template specializations, and the function
4268 // template for F1 is more specialized than the template for F2
4269 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004270 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004271 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4272 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004273 if (FunctionTemplateDecl *BetterTemplate
4274 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4275 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004276 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004277 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4278 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004279 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004280
Douglas Gregora1f013e2008-11-07 22:36:19 +00004281 // -- the context is an initialization by user-defined conversion
4282 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4283 // from the return type of F1 to the destination type (i.e.,
4284 // the type of the entity being initialized) is a better
4285 // conversion sequence than the standard conversion sequence
4286 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004287 if (Cand1.Function && Cand2.Function &&
4288 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004289 isa<CXXConversionDecl>(Cand2.Function)) {
4290 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4291 Cand2.FinalConversion)) {
4292 case ImplicitConversionSequence::Better:
4293 // Cand1 has a better conversion sequence.
4294 return true;
4295
4296 case ImplicitConversionSequence::Worse:
4297 // Cand1 can't be better than Cand2.
4298 return false;
4299
4300 case ImplicitConversionSequence::Indistinguishable:
4301 // Do nothing
4302 break;
4303 }
4304 }
4305
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004306 return false;
4307}
4308
Mike Stump11289f42009-09-09 15:08:12 +00004309/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004310/// within an overload candidate set.
4311///
4312/// \param CandidateSet the set of candidate functions.
4313///
4314/// \param Loc the location of the function name (or operator symbol) for
4315/// which overload resolution occurs.
4316///
Mike Stump11289f42009-09-09 15:08:12 +00004317/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004318/// function, Best points to the candidate function found.
4319///
4320/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004321OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4322 SourceLocation Loc,
4323 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004324 // Find the best viable function.
4325 Best = CandidateSet.end();
4326 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4327 Cand != CandidateSet.end(); ++Cand) {
4328 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004329 if (Best == CandidateSet.end() ||
4330 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004331 Best = Cand;
4332 }
4333 }
4334
4335 // If we didn't find any viable functions, abort.
4336 if (Best == CandidateSet.end())
4337 return OR_No_Viable_Function;
4338
4339 // Make sure that this function is better than every other viable
4340 // function. If not, we have an ambiguity.
4341 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4342 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004343 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004344 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004345 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004346 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004347 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004348 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004349 }
Mike Stump11289f42009-09-09 15:08:12 +00004350
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004351 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004352 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004353 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004354 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004355 return OR_Deleted;
4356
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004357 // C++ [basic.def.odr]p2:
4358 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004359 // when referred to from a potentially-evaluated expression. [Note: this
4360 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004361 // (clause 13), user-defined conversions (12.3.2), allocation function for
4362 // placement new (5.3.4), as well as non-default initialization (8.5).
4363 if (Best->Function)
4364 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004365 return OR_Success;
4366}
4367
John McCall53262c92010-01-12 02:15:36 +00004368namespace {
4369
4370enum OverloadCandidateKind {
4371 oc_function,
4372 oc_method,
4373 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004374 oc_function_template,
4375 oc_method_template,
4376 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004377 oc_implicit_default_constructor,
4378 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004379 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004380};
4381
John McCalle1ac8d12010-01-13 00:25:19 +00004382OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4383 FunctionDecl *Fn,
4384 std::string &Description) {
4385 bool isTemplate = false;
4386
4387 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4388 isTemplate = true;
4389 Description = S.getTemplateArgumentBindingsText(
4390 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4391 }
John McCallfd0b2f82010-01-06 09:43:14 +00004392
4393 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004394 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004395 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004396
John McCall53262c92010-01-12 02:15:36 +00004397 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4398 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004399 }
4400
4401 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4402 // This actually gets spelled 'candidate function' for now, but
4403 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004404 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004405 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004406
4407 assert(Meth->isCopyAssignment()
4408 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004409 return oc_implicit_copy_assignment;
4410 }
4411
John McCalle1ac8d12010-01-13 00:25:19 +00004412 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004413}
4414
4415} // end anonymous namespace
4416
4417// Notes the location of an overload candidate.
4418void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004419 std::string FnDesc;
4420 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4421 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4422 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004423}
4424
John McCall0d1da222010-01-12 00:44:57 +00004425/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4426/// "lead" diagnostic; it will be given two arguments, the source and
4427/// target types of the conversion.
4428void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4429 SourceLocation CaretLoc,
4430 const PartialDiagnostic &PDiag) {
4431 Diag(CaretLoc, PDiag)
4432 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4433 for (AmbiguousConversionSequence::const_iterator
4434 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4435 NoteOverloadCandidate(*I);
4436 }
John McCall12f97bc2010-01-08 04:41:39 +00004437}
4438
John McCall0d1da222010-01-12 00:44:57 +00004439namespace {
4440
John McCall6a61b522010-01-13 09:16:55 +00004441void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4442 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4443 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004444 assert(Cand->Function && "for now, candidate must be a function");
4445 FunctionDecl *Fn = Cand->Function;
4446
4447 // There's a conversion slot for the object argument if this is a
4448 // non-constructor method. Note that 'I' corresponds the
4449 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004450 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004451 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004452 if (I == 0)
4453 isObjectArgument = true;
4454 else
4455 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004456 }
4457
John McCalle1ac8d12010-01-13 00:25:19 +00004458 std::string FnDesc;
4459 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4460
John McCall6a61b522010-01-13 09:16:55 +00004461 Expr *FromExpr = Conv.Bad.FromExpr;
4462 QualType FromTy = Conv.Bad.getFromType();
4463 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004464
John McCallfb7ad0f2010-02-02 02:42:52 +00004465 if (FromTy == S.Context.OverloadTy) {
4466 assert(FromExpr);
4467 Expr *E = FromExpr->IgnoreParens();
4468 if (isa<UnaryOperator>(E))
4469 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004470 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004471
4472 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4473 << (unsigned) FnKind << FnDesc
4474 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4475 << ToTy << Name << I+1;
4476 return;
4477 }
4478
John McCall6d174642010-01-23 08:10:49 +00004479 // Do some hand-waving analysis to see if the non-viability is due
4480 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004481 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4482 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4483 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4484 CToTy = RT->getPointeeType();
4485 else {
4486 // TODO: detect and diagnose the full richness of const mismatches.
4487 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4488 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4489 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4490 }
4491
4492 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4493 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4494 // It is dumb that we have to do this here.
4495 while (isa<ArrayType>(CFromTy))
4496 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4497 while (isa<ArrayType>(CToTy))
4498 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4499
4500 Qualifiers FromQs = CFromTy.getQualifiers();
4501 Qualifiers ToQs = CToTy.getQualifiers();
4502
4503 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4504 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4505 << (unsigned) FnKind << FnDesc
4506 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4507 << FromTy
4508 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4509 << (unsigned) isObjectArgument << I+1;
4510 return;
4511 }
4512
4513 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4514 assert(CVR && "unexpected qualifiers mismatch");
4515
4516 if (isObjectArgument) {
4517 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4518 << (unsigned) FnKind << FnDesc
4519 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4520 << FromTy << (CVR - 1);
4521 } else {
4522 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4523 << (unsigned) FnKind << FnDesc
4524 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4525 << FromTy << (CVR - 1) << I+1;
4526 }
4527 return;
4528 }
4529
John McCall6d174642010-01-23 08:10:49 +00004530 // Diagnose references or pointers to incomplete types differently,
4531 // since it's far from impossible that the incompleteness triggered
4532 // the failure.
4533 QualType TempFromTy = FromTy.getNonReferenceType();
4534 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4535 TempFromTy = PTy->getPointeeType();
4536 if (TempFromTy->isIncompleteType()) {
4537 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4538 << (unsigned) FnKind << FnDesc
4539 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4540 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4541 return;
4542 }
4543
John McCall47000992010-01-14 03:28:57 +00004544 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4546 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004548 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004549}
4550
4551void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4552 unsigned NumFormalArgs) {
4553 // TODO: treat calls to a missing default constructor as a special case
4554
4555 FunctionDecl *Fn = Cand->Function;
4556 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4557
4558 unsigned MinParams = Fn->getMinRequiredArguments();
4559
4560 // at least / at most / exactly
4561 unsigned mode, modeCount;
4562 if (NumFormalArgs < MinParams) {
4563 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4564 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4565 mode = 0; // "at least"
4566 else
4567 mode = 2; // "exactly"
4568 modeCount = MinParams;
4569 } else {
4570 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4571 if (MinParams != FnTy->getNumArgs())
4572 mode = 1; // "at most"
4573 else
4574 mode = 2; // "exactly"
4575 modeCount = FnTy->getNumArgs();
4576 }
4577
4578 std::string Description;
4579 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4580
4581 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4582 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004583}
4584
John McCall8b9ed552010-02-01 18:53:26 +00004585/// Diagnose a failed template-argument deduction.
4586void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4587 Expr **Args, unsigned NumArgs) {
4588 FunctionDecl *Fn = Cand->Function; // pattern
4589
4590 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4591 Cand->DeductionFailure.TemplateParameter);
4592
4593 switch (Cand->DeductionFailure.Result) {
4594 case Sema::TDK_Success:
4595 llvm_unreachable("TDK_success while diagnosing bad deduction");
4596
4597 case Sema::TDK_Incomplete: {
4598 NamedDecl *ParamD;
4599 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4600 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4601 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4602 assert(ParamD && "no parameter found for incomplete deduction result");
4603 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4604 << ParamD->getDeclName();
4605 return;
4606 }
4607
4608 // TODO: diagnose these individually, then kill off
4609 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4610 case Sema::TDK_InstantiationDepth:
4611 case Sema::TDK_Inconsistent:
4612 case Sema::TDK_InconsistentQuals:
4613 case Sema::TDK_SubstitutionFailure:
4614 case Sema::TDK_NonDeducedMismatch:
4615 case Sema::TDK_TooManyArguments:
4616 case Sema::TDK_TooFewArguments:
4617 case Sema::TDK_InvalidExplicitArguments:
4618 case Sema::TDK_FailedOverloadResolution:
4619 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4620 return;
4621 }
4622}
4623
4624/// Generates a 'note' diagnostic for an overload candidate. We've
4625/// already generated a primary error at the call site.
4626///
4627/// It really does need to be a single diagnostic with its caret
4628/// pointed at the candidate declaration. Yes, this creates some
4629/// major challenges of technical writing. Yes, this makes pointing
4630/// out problems with specific arguments quite awkward. It's still
4631/// better than generating twenty screens of text for every failed
4632/// overload.
4633///
4634/// It would be great to be able to express per-candidate problems
4635/// more richly for those diagnostic clients that cared, but we'd
4636/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004637void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4638 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004639 FunctionDecl *Fn = Cand->Function;
4640
John McCall12f97bc2010-01-08 04:41:39 +00004641 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004642 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004643 std::string FnDesc;
4644 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004645
4646 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004647 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004648 return;
John McCall12f97bc2010-01-08 04:41:39 +00004649 }
4650
John McCalle1ac8d12010-01-13 00:25:19 +00004651 // We don't really have anything else to say about viable candidates.
4652 if (Cand->Viable) {
4653 S.NoteOverloadCandidate(Fn);
4654 return;
4655 }
John McCall0d1da222010-01-12 00:44:57 +00004656
John McCall6a61b522010-01-13 09:16:55 +00004657 switch (Cand->FailureKind) {
4658 case ovl_fail_too_many_arguments:
4659 case ovl_fail_too_few_arguments:
4660 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004661
John McCall6a61b522010-01-13 09:16:55 +00004662 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004663 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4664
John McCallfe796dd2010-01-23 05:17:32 +00004665 case ovl_fail_trivial_conversion:
4666 case ovl_fail_bad_final_conversion:
John McCall6a61b522010-01-13 09:16:55 +00004667 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004668
John McCall6a61b522010-01-13 09:16:55 +00004669 case ovl_fail_bad_conversion:
4670 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4671 if (Cand->Conversions[I].isBad())
4672 return DiagnoseBadConversion(S, Cand, I);
4673
4674 // FIXME: this currently happens when we're called from SemaInit
4675 // when user-conversion overload fails. Figure out how to handle
4676 // those conditions and diagnose them well.
4677 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004678 }
John McCalld3224162010-01-08 00:58:21 +00004679}
4680
4681void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4682 // Desugar the type of the surrogate down to a function type,
4683 // retaining as many typedefs as possible while still showing
4684 // the function type (and, therefore, its parameter types).
4685 QualType FnType = Cand->Surrogate->getConversionType();
4686 bool isLValueReference = false;
4687 bool isRValueReference = false;
4688 bool isPointer = false;
4689 if (const LValueReferenceType *FnTypeRef =
4690 FnType->getAs<LValueReferenceType>()) {
4691 FnType = FnTypeRef->getPointeeType();
4692 isLValueReference = true;
4693 } else if (const RValueReferenceType *FnTypeRef =
4694 FnType->getAs<RValueReferenceType>()) {
4695 FnType = FnTypeRef->getPointeeType();
4696 isRValueReference = true;
4697 }
4698 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4699 FnType = FnTypePtr->getPointeeType();
4700 isPointer = true;
4701 }
4702 // Desugar down to a function type.
4703 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4704 // Reconstruct the pointer/reference as appropriate.
4705 if (isPointer) FnType = S.Context.getPointerType(FnType);
4706 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4707 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4708
4709 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4710 << FnType;
4711}
4712
4713void NoteBuiltinOperatorCandidate(Sema &S,
4714 const char *Opc,
4715 SourceLocation OpLoc,
4716 OverloadCandidate *Cand) {
4717 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4718 std::string TypeStr("operator");
4719 TypeStr += Opc;
4720 TypeStr += "(";
4721 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4722 if (Cand->Conversions.size() == 1) {
4723 TypeStr += ")";
4724 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4725 } else {
4726 TypeStr += ", ";
4727 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4728 TypeStr += ")";
4729 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4730 }
4731}
4732
4733void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4734 OverloadCandidate *Cand) {
4735 unsigned NoOperands = Cand->Conversions.size();
4736 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4737 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004738 if (ICS.isBad()) break; // all meaningless after first invalid
4739 if (!ICS.isAmbiguous()) continue;
4740
4741 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4742 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004743 }
4744}
4745
John McCall3712d9e2010-01-15 23:32:50 +00004746SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4747 if (Cand->Function)
4748 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00004749 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00004750 return Cand->Surrogate->getLocation();
4751 return SourceLocation();
4752}
4753
John McCallad2587a2010-01-12 00:48:53 +00004754struct CompareOverloadCandidatesForDisplay {
4755 Sema &S;
4756 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004757
4758 bool operator()(const OverloadCandidate *L,
4759 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00004760 // Fast-path this check.
4761 if (L == R) return false;
4762
John McCall12f97bc2010-01-08 04:41:39 +00004763 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004764 if (L->Viable) {
4765 if (!R->Viable) return true;
4766
4767 // TODO: introduce a tri-valued comparison for overload
4768 // candidates. Would be more worthwhile if we had a sort
4769 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00004770 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4771 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00004772 } else if (R->Viable)
4773 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004774
John McCall3712d9e2010-01-15 23:32:50 +00004775 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004776
John McCall3712d9e2010-01-15 23:32:50 +00004777 // Criteria by which we can sort non-viable candidates:
4778 if (!L->Viable) {
4779 // 1. Arity mismatches come after other candidates.
4780 if (L->FailureKind == ovl_fail_too_many_arguments ||
4781 L->FailureKind == ovl_fail_too_few_arguments)
4782 return false;
4783 if (R->FailureKind == ovl_fail_too_many_arguments ||
4784 R->FailureKind == ovl_fail_too_few_arguments)
4785 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004786
John McCallfe796dd2010-01-23 05:17:32 +00004787 // 2. Bad conversions come first and are ordered by the number
4788 // of bad conversions and quality of good conversions.
4789 if (L->FailureKind == ovl_fail_bad_conversion) {
4790 if (R->FailureKind != ovl_fail_bad_conversion)
4791 return true;
4792
4793 // If there's any ordering between the defined conversions...
4794 // FIXME: this might not be transitive.
4795 assert(L->Conversions.size() == R->Conversions.size());
4796
4797 int leftBetter = 0;
4798 for (unsigned I = 0, E = L->Conversions.size(); I != E; ++I) {
4799 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4800 R->Conversions[I])) {
4801 case ImplicitConversionSequence::Better:
4802 leftBetter++;
4803 break;
4804
4805 case ImplicitConversionSequence::Worse:
4806 leftBetter--;
4807 break;
4808
4809 case ImplicitConversionSequence::Indistinguishable:
4810 break;
4811 }
4812 }
4813 if (leftBetter > 0) return true;
4814 if (leftBetter < 0) return false;
4815
4816 } else if (R->FailureKind == ovl_fail_bad_conversion)
4817 return false;
4818
John McCall3712d9e2010-01-15 23:32:50 +00004819 // TODO: others?
4820 }
4821
4822 // Sort everything else by location.
4823 SourceLocation LLoc = GetLocationForCandidate(L);
4824 SourceLocation RLoc = GetLocationForCandidate(R);
4825
4826 // Put candidates without locations (e.g. builtins) at the end.
4827 if (LLoc.isInvalid()) return false;
4828 if (RLoc.isInvalid()) return true;
4829
4830 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004831 }
4832};
4833
John McCallfe796dd2010-01-23 05:17:32 +00004834/// CompleteNonViableCandidate - Normally, overload resolution only
4835/// computes up to the first
4836void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4837 Expr **Args, unsigned NumArgs) {
4838 assert(!Cand->Viable);
4839
4840 // Don't do anything on failures other than bad conversion.
4841 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4842
4843 // Skip forward to the first bad conversion.
4844 unsigned ConvIdx = 0;
4845 unsigned ConvCount = Cand->Conversions.size();
4846 while (true) {
4847 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4848 ConvIdx++;
4849 if (Cand->Conversions[ConvIdx - 1].isBad())
4850 break;
4851 }
4852
4853 if (ConvIdx == ConvCount)
4854 return;
4855
4856 // FIXME: these should probably be preserved from the overload
4857 // operation somehow.
4858 bool SuppressUserConversions = false;
4859 bool ForceRValue = false;
4860
4861 const FunctionProtoType* Proto;
4862 unsigned ArgIdx = ConvIdx;
4863
4864 if (Cand->IsSurrogate) {
4865 QualType ConvType
4866 = Cand->Surrogate->getConversionType().getNonReferenceType();
4867 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4868 ConvType = ConvPtrType->getPointeeType();
4869 Proto = ConvType->getAs<FunctionProtoType>();
4870 ArgIdx--;
4871 } else if (Cand->Function) {
4872 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4873 if (isa<CXXMethodDecl>(Cand->Function) &&
4874 !isa<CXXConstructorDecl>(Cand->Function))
4875 ArgIdx--;
4876 } else {
4877 // Builtin binary operator with a bad first conversion.
4878 assert(ConvCount <= 3);
4879 for (; ConvIdx != ConvCount; ++ConvIdx)
4880 Cand->Conversions[ConvIdx]
4881 = S.TryCopyInitialization(Args[ConvIdx],
4882 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4883 SuppressUserConversions, ForceRValue,
4884 /*InOverloadResolution*/ true);
4885 return;
4886 }
4887
4888 // Fill in the rest of the conversions.
4889 unsigned NumArgsInProto = Proto->getNumArgs();
4890 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4891 if (ArgIdx < NumArgsInProto)
4892 Cand->Conversions[ConvIdx]
4893 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4894 SuppressUserConversions, ForceRValue,
4895 /*InOverloadResolution=*/true);
4896 else
4897 Cand->Conversions[ConvIdx].setEllipsis();
4898 }
4899}
4900
John McCalld3224162010-01-08 00:58:21 +00004901} // end anonymous namespace
4902
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004903/// PrintOverloadCandidates - When overload resolution fails, prints
4904/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004905/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004906void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004907Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004908 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004909 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004910 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004911 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004912 // Sort the candidates by viability and position. Sorting directly would
4913 // be prohibitive, so we make a set of pointers and sort those.
4914 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4915 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4916 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4917 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00004918 Cand != LastCand; ++Cand) {
4919 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00004920 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00004921 else if (OCD == OCD_AllCandidates) {
4922 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4923 Cands.push_back(Cand);
4924 }
4925 }
4926
John McCallad2587a2010-01-12 00:48:53 +00004927 std::sort(Cands.begin(), Cands.end(),
4928 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004929
John McCall0d1da222010-01-12 00:44:57 +00004930 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004931
John McCall12f97bc2010-01-08 04:41:39 +00004932 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4933 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4934 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004935
John McCalld3224162010-01-08 00:58:21 +00004936 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004937 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004938 else if (Cand->IsSurrogate)
4939 NoteSurrogateCandidate(*this, Cand);
4940
4941 // This a builtin candidate. We do not, in general, want to list
4942 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004943 else if (Cand->Viable) {
4944 // Generally we only see ambiguities including viable builtin
4945 // operators if overload resolution got screwed up by an
4946 // ambiguous user-defined conversion.
4947 //
4948 // FIXME: It's quite possible for different conversions to see
4949 // different ambiguities, though.
4950 if (!ReportedAmbiguousConversions) {
4951 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4952 ReportedAmbiguousConversions = true;
4953 }
John McCalld3224162010-01-08 00:58:21 +00004954
John McCall0d1da222010-01-12 00:44:57 +00004955 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004956 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004957 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004958 }
4959}
4960
John McCall1acbbb52010-02-02 06:20:04 +00004961static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, NamedDecl *D,
John McCall58cc69d2010-01-27 01:50:18 +00004962 AccessSpecifier AS) {
4963 if (isa<UnresolvedLookupExpr>(E))
4964 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D, AS);
4965
4966 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D, AS);
4967}
4968
Douglas Gregorcd695e52008-11-10 20:40:00 +00004969/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4970/// an overloaded function (C++ [over.over]), where @p From is an
4971/// expression with overloaded function type and @p ToType is the type
4972/// we're trying to resolve to. For example:
4973///
4974/// @code
4975/// int f(double);
4976/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004977///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004978/// int (*pfd)(double) = f; // selects f(double)
4979/// @endcode
4980///
4981/// This routine returns the resulting FunctionDecl if it could be
4982/// resolved, and NULL otherwise. When @p Complain is true, this
4983/// routine will emit diagnostics if there is an error.
4984FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004985Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004986 bool Complain) {
4987 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004988 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004989 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004990 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004991 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004992 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004993 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004994 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004995 FunctionType = MemTypePtr->getPointeeType();
4996 IsMember = true;
4997 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004998
4999 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00005000 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00005001 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005002 return 0;
5003
5004 // Find the actual overloaded function declaration.
John McCall1acbbb52010-02-02 06:20:04 +00005005 if (From->getType() != Context.OverloadTy)
5006 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005007
Douglas Gregorcd695e52008-11-10 20:40:00 +00005008 // C++ [over.over]p1:
5009 // [...] [Note: any redundant set of parentheses surrounding the
5010 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005011 // C++ [over.over]p1:
5012 // [...] The overloaded function name can be preceded by the &
5013 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005014 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5015 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5016 if (OvlExpr->hasExplicitTemplateArgs()) {
5017 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5018 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005019 }
5020
Douglas Gregorcd695e52008-11-10 20:40:00 +00005021 // Look through all of the overloaded functions, searching for one
5022 // whose type matches exactly.
John McCall58cc69d2010-01-27 01:50:18 +00005023 UnresolvedSet<4> Matches; // contains only FunctionDecls
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005024 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005025 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5026 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005027 // Look through any using declarations to find the underlying function.
5028 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5029
Douglas Gregorcd695e52008-11-10 20:40:00 +00005030 // C++ [over.over]p3:
5031 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005032 // targets of type "pointer-to-function" or "reference-to-function."
5033 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005034 // type "pointer-to-member-function."
5035 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005036
Mike Stump11289f42009-09-09 15:08:12 +00005037 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005038 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005039 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005040 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005041 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005042 // static when converting to member pointer.
5043 if (Method->isStatic() == IsMember)
5044 continue;
5045 } else if (IsMember)
5046 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005047
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005048 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005049 // If the name is a function template, template argument deduction is
5050 // done (14.8.2.2), and if the argument deduction succeeds, the
5051 // resulting template argument list is used to generate a single
5052 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005053 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005054 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005055 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005056 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005057 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005058 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005059 FunctionType, Specialization, Info)) {
5060 // FIXME: make a note of the failed deduction for diagnostics.
5061 (void)Result;
5062 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005063 // FIXME: If the match isn't exact, shouldn't we just drop this as
5064 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005065 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005066 == Context.getCanonicalType(Specialization->getType()));
John McCall58cc69d2010-01-27 01:50:18 +00005067 Matches.addDecl(cast<FunctionDecl>(Specialization->getCanonicalDecl()),
5068 I.getAccess());
Douglas Gregor9b146582009-07-08 20:55:45 +00005069 }
John McCalld14a8642009-11-21 08:51:07 +00005070
5071 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005072 }
Mike Stump11289f42009-09-09 15:08:12 +00005073
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005074 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005075 // Skip non-static functions when converting to pointer, and static
5076 // when converting to member pointer.
5077 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005078 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005079
5080 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005081 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005082 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005083 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005084 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005085
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005086 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005087 QualType ResultTy;
5088 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5089 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5090 ResultTy)) {
John McCall58cc69d2010-01-27 01:50:18 +00005091 Matches.addDecl(cast<FunctionDecl>(FunDecl->getCanonicalDecl()),
5092 I.getAccess());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005093 FoundNonTemplateFunction = true;
5094 }
Mike Stump11289f42009-09-09 15:08:12 +00005095 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005096 }
5097
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005098 // If there were 0 or 1 matches, we're done.
5099 if (Matches.empty())
5100 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005101 else if (Matches.size() == 1) {
John McCall58cc69d2010-01-27 01:50:18 +00005102 FunctionDecl *Result = cast<FunctionDecl>(*Matches.begin());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005103 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005104 if (Complain)
5105 CheckUnresolvedAccess(*this, OvlExpr, Result, Matches.begin().getAccess());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005106 return Result;
5107 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005108
5109 // C++ [over.over]p4:
5110 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005111 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005112 // [...] and any given function template specialization F1 is
5113 // eliminated if the set contains a second function template
5114 // specialization whose function template is more specialized
5115 // than the function template of F1 according to the partial
5116 // ordering rules of 14.5.5.2.
5117
5118 // The algorithm specified above is quadratic. We instead use a
5119 // two-pass algorithm (similar to the one used to identify the
5120 // best viable function in an overload set) that identifies the
5121 // best function template (if it exists).
John McCall58cc69d2010-01-27 01:50:18 +00005122
5123 UnresolvedSetIterator Result =
5124 getMostSpecialized(Matches.begin(), Matches.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005125 TPOC_Other, From->getLocStart(),
5126 PDiag(),
5127 PDiag(diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005128 << Matches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005129 PDiag(diag::note_ovl_candidate)
5130 << (unsigned) oc_function_template);
John McCall58cc69d2010-01-27 01:50:18 +00005131 assert(Result != Matches.end() && "no most-specialized template");
5132 MarkDeclarationReferenced(From->getLocStart(), *Result);
5133 if (Complain)
5134 CheckUnresolvedAccess(*this, OvlExpr, *Result, Result.getAccess());
5135 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005136 }
Mike Stump11289f42009-09-09 15:08:12 +00005137
Douglas Gregorfae1d712009-09-26 03:56:17 +00005138 // [...] any function template specializations in the set are
5139 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005140 for (unsigned I = 0, N = Matches.size(); I != N; ) {
5141 if (cast<FunctionDecl>(Matches[I].getDecl())->getPrimaryTemplate() == 0)
5142 ++I;
5143 else {
5144 Matches.erase(I);
5145 --N;
5146 }
5147 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005148
Mike Stump11289f42009-09-09 15:08:12 +00005149 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005150 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005151 if (Matches.size() == 1) {
5152 UnresolvedSetIterator Match = Matches.begin();
5153 MarkDeclarationReferenced(From->getLocStart(), *Match);
5154 if (Complain)
5155 CheckUnresolvedAccess(*this, OvlExpr, *Match, Match.getAccess());
5156 return cast<FunctionDecl>(*Match);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005157 }
Mike Stump11289f42009-09-09 15:08:12 +00005158
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005159 // FIXME: We should probably return the same thing that BestViableFunction
5160 // returns (even if we issue the diagnostics here).
5161 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005162 << Matches[0]->getDeclName();
5163 for (UnresolvedSetIterator I = Matches.begin(),
5164 E = Matches.end(); I != E; ++I)
5165 NoteOverloadCandidate(cast<FunctionDecl>(*I));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005166 return 0;
5167}
5168
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005169/// \brief Given an expression that refers to an overloaded function, try to
5170/// resolve that overloaded function expression down to a single function.
5171///
5172/// This routine can only resolve template-ids that refer to a single function
5173/// template, where that template-id refers to a single template whose template
5174/// arguments are either provided by the template-id or have defaults,
5175/// as described in C++0x [temp.arg.explicit]p3.
5176FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5177 // C++ [over.over]p1:
5178 // [...] [Note: any redundant set of parentheses surrounding the
5179 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005180 // C++ [over.over]p1:
5181 // [...] The overloaded function name can be preceded by the &
5182 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005183
5184 if (From->getType() != Context.OverloadTy)
5185 return 0;
5186
5187 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005188
5189 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005190 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005191 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005192
5193 TemplateArgumentListInfo ExplicitTemplateArgs;
5194 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005195
5196 // Look through all of the overloaded functions, searching for one
5197 // whose type matches exactly.
5198 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005199 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5200 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005201 // C++0x [temp.arg.explicit]p3:
5202 // [...] In contexts where deduction is done and fails, or in contexts
5203 // where deduction is not done, if a template argument list is
5204 // specified and it, along with any default template arguments,
5205 // identifies a single function template specialization, then the
5206 // template-id is an lvalue for the function template specialization.
5207 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5208
5209 // C++ [over.over]p2:
5210 // If the name is a function template, template argument deduction is
5211 // done (14.8.2.2), and if the argument deduction succeeds, the
5212 // resulting template argument list is used to generate a single
5213 // function template specialization, which is added to the set of
5214 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005215 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005216 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005217 if (TemplateDeductionResult Result
5218 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5219 Specialization, Info)) {
5220 // FIXME: make a note of the failed deduction for diagnostics.
5221 (void)Result;
5222 continue;
5223 }
5224
5225 // Multiple matches; we can't resolve to a single declaration.
5226 if (Matched)
5227 return 0;
5228
5229 Matched = Specialization;
5230 }
5231
5232 return Matched;
5233}
5234
Douglas Gregorcabea402009-09-22 15:41:20 +00005235/// \brief Add a single candidate to the overload set.
5236static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00005237 NamedDecl *Callee,
John McCallb89836b2010-01-26 01:37:31 +00005238 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00005239 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005240 Expr **Args, unsigned NumArgs,
5241 OverloadCandidateSet &CandidateSet,
5242 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005243 if (isa<UsingShadowDecl>(Callee))
5244 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5245
Douglas Gregorcabea402009-09-22 15:41:20 +00005246 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005247 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCallb89836b2010-01-26 01:37:31 +00005248 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5249 false, false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005250 return;
John McCalld14a8642009-11-21 08:51:07 +00005251 }
5252
5253 if (FunctionTemplateDecl *FuncTemplate
5254 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCallb89836b2010-01-26 01:37:31 +00005255 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005256 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005257 return;
5258 }
5259
5260 assert(false && "unhandled case in overloaded call candidate");
5261
5262 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005263}
5264
5265/// \brief Add the overload candidates named by callee and/or found by argument
5266/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005267void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005268 Expr **Args, unsigned NumArgs,
5269 OverloadCandidateSet &CandidateSet,
5270 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005271
5272#ifndef NDEBUG
5273 // Verify that ArgumentDependentLookup is consistent with the rules
5274 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005275 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005276 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5277 // and let Y be the lookup set produced by argument dependent
5278 // lookup (defined as follows). If X contains
5279 //
5280 // -- a declaration of a class member, or
5281 //
5282 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005283 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005284 //
5285 // -- a declaration that is neither a function or a function
5286 // template
5287 //
5288 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005289
John McCall57500772009-12-16 12:17:52 +00005290 if (ULE->requiresADL()) {
5291 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5292 E = ULE->decls_end(); I != E; ++I) {
5293 assert(!(*I)->getDeclContext()->isRecord());
5294 assert(isa<UsingShadowDecl>(*I) ||
5295 !(*I)->getDeclContext()->isFunctionOrMethod());
5296 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005297 }
5298 }
5299#endif
5300
John McCall57500772009-12-16 12:17:52 +00005301 // It would be nice to avoid this copy.
5302 TemplateArgumentListInfo TABuffer;
5303 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5304 if (ULE->hasExplicitTemplateArgs()) {
5305 ULE->copyTemplateArgumentsInto(TABuffer);
5306 ExplicitTemplateArgs = &TABuffer;
5307 }
5308
5309 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5310 E = ULE->decls_end(); I != E; ++I)
John McCallb89836b2010-01-26 01:37:31 +00005311 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005312 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005313 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005314
John McCall57500772009-12-16 12:17:52 +00005315 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005316 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5317 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005318 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005319 CandidateSet,
5320 PartialOverloading);
5321}
John McCalld681c392009-12-16 08:11:27 +00005322
John McCall57500772009-12-16 12:17:52 +00005323static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5324 Expr **Args, unsigned NumArgs) {
5325 Fn->Destroy(SemaRef.Context);
5326 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5327 Args[Arg]->Destroy(SemaRef.Context);
5328 return SemaRef.ExprError();
5329}
5330
John McCalld681c392009-12-16 08:11:27 +00005331/// Attempts to recover from a call where no functions were found.
5332///
5333/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005334static Sema::OwningExprResult
5335BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5336 UnresolvedLookupExpr *ULE,
5337 SourceLocation LParenLoc,
5338 Expr **Args, unsigned NumArgs,
5339 SourceLocation *CommaLocs,
5340 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005341
5342 CXXScopeSpec SS;
5343 if (ULE->getQualifier()) {
5344 SS.setScopeRep(ULE->getQualifier());
5345 SS.setRange(ULE->getQualifierRange());
5346 }
5347
John McCall57500772009-12-16 12:17:52 +00005348 TemplateArgumentListInfo TABuffer;
5349 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5350 if (ULE->hasExplicitTemplateArgs()) {
5351 ULE->copyTemplateArgumentsInto(TABuffer);
5352 ExplicitTemplateArgs = &TABuffer;
5353 }
5354
John McCalld681c392009-12-16 08:11:27 +00005355 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5356 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005357 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005358 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005359
John McCall57500772009-12-16 12:17:52 +00005360 assert(!R.empty() && "lookup results empty despite recovery");
5361
5362 // Build an implicit member call if appropriate. Just drop the
5363 // casts and such from the call, we don't really care.
5364 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5365 if ((*R.begin())->isCXXClassMember())
5366 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5367 else if (ExplicitTemplateArgs)
5368 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5369 else
5370 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5371
5372 if (NewFn.isInvalid())
5373 return Destroy(SemaRef, Fn, Args, NumArgs);
5374
5375 Fn->Destroy(SemaRef.Context);
5376
5377 // This shouldn't cause an infinite loop because we're giving it
5378 // an expression with non-empty lookup results, which should never
5379 // end up here.
5380 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5381 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5382 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005383}
Douglas Gregorcabea402009-09-22 15:41:20 +00005384
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005385/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005386/// (which eventually refers to the declaration Func) and the call
5387/// arguments Args/NumArgs, attempt to resolve the function call down
5388/// to a specific function. If overload resolution succeeds, returns
5389/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005390/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005391/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005392Sema::OwningExprResult
5393Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5394 SourceLocation LParenLoc,
5395 Expr **Args, unsigned NumArgs,
5396 SourceLocation *CommaLocs,
5397 SourceLocation RParenLoc) {
5398#ifndef NDEBUG
5399 if (ULE->requiresADL()) {
5400 // To do ADL, we must have found an unqualified name.
5401 assert(!ULE->getQualifier() && "qualified name with ADL");
5402
5403 // We don't perform ADL for implicit declarations of builtins.
5404 // Verify that this was correctly set up.
5405 FunctionDecl *F;
5406 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5407 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5408 F->getBuiltinID() && F->isImplicit())
5409 assert(0 && "performing ADL for builtin");
5410
5411 // We don't perform ADL in C.
5412 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5413 }
5414#endif
5415
John McCallbc077cf2010-02-08 23:07:23 +00005416 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005417
John McCall57500772009-12-16 12:17:52 +00005418 // Add the functions denoted by the callee to the set of candidate
5419 // functions, including those from argument-dependent lookup.
5420 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005421
5422 // If we found nothing, try to recover.
5423 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5424 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005425 if (CandidateSet.empty())
5426 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5427 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005428
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005429 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005430 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005431 case OR_Success: {
5432 FunctionDecl *FDecl = Best->Function;
John McCall58cc69d2010-01-27 01:50:18 +00005433 CheckUnresolvedLookupAccess(ULE, FDecl, Best->getAccess());
John McCall57500772009-12-16 12:17:52 +00005434 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5435 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5436 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005437
5438 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005439 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005440 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005441 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005442 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005443 break;
5444
5445 case OR_Ambiguous:
5446 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005447 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005448 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005449 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005450
5451 case OR_Deleted:
5452 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5453 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005454 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005455 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005456 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005457 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005458 }
5459
5460 // Overload resolution failed. Destroy all of the subexpressions and
5461 // return NULL.
5462 Fn->Destroy(Context);
5463 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5464 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005465 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005466}
5467
John McCall4c4c1df2010-01-26 03:27:55 +00005468static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005469 return Functions.size() > 1 ||
5470 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5471}
5472
Douglas Gregor084d8552009-03-13 23:49:33 +00005473/// \brief Create a unary operation that may resolve to an overloaded
5474/// operator.
5475///
5476/// \param OpLoc The location of the operator itself (e.g., '*').
5477///
5478/// \param OpcIn The UnaryOperator::Opcode that describes this
5479/// operator.
5480///
5481/// \param Functions The set of non-member functions that will be
5482/// considered by overload resolution. The caller needs to build this
5483/// set based on the context using, e.g.,
5484/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5485/// set should not contain any member functions; those will be added
5486/// by CreateOverloadedUnaryOp().
5487///
5488/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005489Sema::OwningExprResult
5490Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5491 const UnresolvedSetImpl &Fns,
5492 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005493 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5494 Expr *Input = (Expr *)input.get();
5495
5496 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5497 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5498 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5499
5500 Expr *Args[2] = { Input, 0 };
5501 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005502
Douglas Gregor084d8552009-03-13 23:49:33 +00005503 // For post-increment and post-decrement, add the implicit '0' as
5504 // the second argument, so that we know this is a post-increment or
5505 // post-decrement.
5506 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5507 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005508 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005509 SourceLocation());
5510 NumArgs = 2;
5511 }
5512
5513 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005514 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005515 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005516 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005517 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005518 /*ADL*/ true, IsOverloaded(Fns));
5519 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005520
Douglas Gregor084d8552009-03-13 23:49:33 +00005521 input.release();
5522 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5523 &Args[0], NumArgs,
5524 Context.DependentTy,
5525 OpLoc));
5526 }
5527
5528 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005529 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005530
5531 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005532 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005533
5534 // Add operator candidates that are member functions.
5535 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5536
John McCall4c4c1df2010-01-26 03:27:55 +00005537 // Add candidates from ADL.
5538 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005539 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005540 /*ExplicitTemplateArgs*/ 0,
5541 CandidateSet);
5542
Douglas Gregor084d8552009-03-13 23:49:33 +00005543 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005544 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005545
5546 // Perform overload resolution.
5547 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005548 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005549 case OR_Success: {
5550 // We found a built-in operator or an overloaded operator.
5551 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005552
Douglas Gregor084d8552009-03-13 23:49:33 +00005553 if (FnDecl) {
5554 // We matched an overloaded operator. Build a call to that
5555 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005556
Douglas Gregor084d8552009-03-13 23:49:33 +00005557 // Convert the arguments.
5558 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005559 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5560
Douglas Gregor084d8552009-03-13 23:49:33 +00005561 if (PerformObjectArgumentInitialization(Input, Method))
5562 return ExprError();
5563 } else {
5564 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005565 OwningExprResult InputInit
5566 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005567 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005568 SourceLocation(),
5569 move(input));
5570 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005571 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005572
Douglas Gregore6600372009-12-23 17:40:29 +00005573 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005574 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005575 }
5576
5577 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005578 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005579
Douglas Gregor084d8552009-03-13 23:49:33 +00005580 // Build the actual expression node.
5581 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5582 SourceLocation());
5583 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005584
Douglas Gregor084d8552009-03-13 23:49:33 +00005585 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005586 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005587 ExprOwningPtr<CallExpr> TheCall(this,
5588 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005589 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005590
5591 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5592 FnDecl))
5593 return ExprError();
5594
5595 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005596 } else {
5597 // We matched a built-in operator. Convert the arguments, then
5598 // break out so that we will build the appropriate built-in
5599 // operator node.
5600 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005601 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005602 return ExprError();
5603
5604 break;
5605 }
5606 }
5607
5608 case OR_No_Viable_Function:
5609 // No viable function; fall through to handling this as a
5610 // built-in operator, which will produce an error message for us.
5611 break;
5612
5613 case OR_Ambiguous:
5614 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5615 << UnaryOperator::getOpcodeStr(Opc)
5616 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005617 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005618 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005619 return ExprError();
5620
5621 case OR_Deleted:
5622 Diag(OpLoc, diag::err_ovl_deleted_oper)
5623 << Best->Function->isDeleted()
5624 << UnaryOperator::getOpcodeStr(Opc)
5625 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005626 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005627 return ExprError();
5628 }
5629
5630 // Either we found no viable overloaded operator or we matched a
5631 // built-in operator. In either case, fall through to trying to
5632 // build a built-in operation.
5633 input.release();
5634 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5635}
5636
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005637/// \brief Create a binary operation that may resolve to an overloaded
5638/// operator.
5639///
5640/// \param OpLoc The location of the operator itself (e.g., '+').
5641///
5642/// \param OpcIn The BinaryOperator::Opcode that describes this
5643/// operator.
5644///
5645/// \param Functions The set of non-member functions that will be
5646/// considered by overload resolution. The caller needs to build this
5647/// set based on the context using, e.g.,
5648/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5649/// set should not contain any member functions; those will be added
5650/// by CreateOverloadedBinOp().
5651///
5652/// \param LHS Left-hand argument.
5653/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005654Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005655Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005656 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005657 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005658 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005659 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005660 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005661
5662 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5663 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5664 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5665
5666 // If either side is type-dependent, create an appropriate dependent
5667 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005668 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00005669 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005670 // If there are no functions to store, just build a dependent
5671 // BinaryOperator or CompoundAssignment.
5672 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5673 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5674 Context.DependentTy, OpLoc));
5675
5676 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5677 Context.DependentTy,
5678 Context.DependentTy,
5679 Context.DependentTy,
5680 OpLoc));
5681 }
John McCall4c4c1df2010-01-26 03:27:55 +00005682
5683 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00005684 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005685 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005686 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005687 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005688 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00005689
John McCall4c4c1df2010-01-26 03:27:55 +00005690 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005691 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005692 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005693 Context.DependentTy,
5694 OpLoc));
5695 }
5696
5697 // If this is the .* operator, which is not overloadable, just
5698 // create a built-in binary operator.
5699 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005700 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005701
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005702 // If this is the assignment operator, we only perform overload resolution
5703 // if the left-hand side is a class or enumeration type. This is actually
5704 // a hack. The standard requires that we do overload resolution between the
5705 // various built-in candidates, but as DR507 points out, this can lead to
5706 // problems. So we do it this way, which pretty much follows what GCC does.
5707 // Note that we go the traditional code path for compound assignment forms.
5708 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005709 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005710
Douglas Gregor084d8552009-03-13 23:49:33 +00005711 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005712 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005713
5714 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005715 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005716
5717 // Add operator candidates that are member functions.
5718 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5719
John McCall4c4c1df2010-01-26 03:27:55 +00005720 // Add candidates from ADL.
5721 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5722 Args, 2,
5723 /*ExplicitTemplateArgs*/ 0,
5724 CandidateSet);
5725
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005726 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005727 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005728
5729 // Perform overload resolution.
5730 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005731 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005732 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005733 // We found a built-in operator or an overloaded operator.
5734 FunctionDecl *FnDecl = Best->Function;
5735
5736 if (FnDecl) {
5737 // We matched an overloaded operator. Build a call to that
5738 // operator.
5739
5740 // Convert the arguments.
5741 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005742 // Best->Access is only meaningful for class members.
5743 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5744
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005745 OwningExprResult Arg1
5746 = PerformCopyInitialization(
5747 InitializedEntity::InitializeParameter(
5748 FnDecl->getParamDecl(0)),
5749 SourceLocation(),
5750 Owned(Args[1]));
5751 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005752 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005753
5754 if (PerformObjectArgumentInitialization(Args[0], Method))
5755 return ExprError();
5756
5757 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005758 } else {
5759 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005760 OwningExprResult Arg0
5761 = PerformCopyInitialization(
5762 InitializedEntity::InitializeParameter(
5763 FnDecl->getParamDecl(0)),
5764 SourceLocation(),
5765 Owned(Args[0]));
5766 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005767 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005768
5769 OwningExprResult Arg1
5770 = PerformCopyInitialization(
5771 InitializedEntity::InitializeParameter(
5772 FnDecl->getParamDecl(1)),
5773 SourceLocation(),
5774 Owned(Args[1]));
5775 if (Arg1.isInvalid())
5776 return ExprError();
5777 Args[0] = LHS = Arg0.takeAs<Expr>();
5778 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005779 }
5780
5781 // Determine the result type
5782 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005783 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005784 ResultTy = ResultTy.getNonReferenceType();
5785
5786 // Build the actual expression node.
5787 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005788 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005789 UsualUnaryConversions(FnExpr);
5790
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005791 ExprOwningPtr<CXXOperatorCallExpr>
5792 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5793 Args, 2, ResultTy,
5794 OpLoc));
5795
5796 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5797 FnDecl))
5798 return ExprError();
5799
5800 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005801 } else {
5802 // We matched a built-in operator. Convert the arguments, then
5803 // break out so that we will build the appropriate built-in
5804 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005805 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005806 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005807 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005808 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005809 return ExprError();
5810
5811 break;
5812 }
5813 }
5814
Douglas Gregor66950a32009-09-30 21:46:01 +00005815 case OR_No_Viable_Function: {
5816 // C++ [over.match.oper]p9:
5817 // If the operator is the operator , [...] and there are no
5818 // viable functions, then the operator is assumed to be the
5819 // built-in operator and interpreted according to clause 5.
5820 if (Opc == BinaryOperator::Comma)
5821 break;
5822
Sebastian Redl027de2a2009-05-21 11:50:50 +00005823 // For class as left operand for assignment or compound assigment operator
5824 // do not fall through to handling in built-in, but report that no overloaded
5825 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005826 OwningExprResult Result = ExprError();
5827 if (Args[0]->getType()->isRecordType() &&
5828 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005829 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5830 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005831 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005832 } else {
5833 // No viable function; try to create a built-in operation, which will
5834 // produce an error. Then, show the non-viable candidates.
5835 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005836 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005837 assert(Result.isInvalid() &&
5838 "C++ binary operator overloading is missing candidates!");
5839 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005840 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005841 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005842 return move(Result);
5843 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005844
5845 case OR_Ambiguous:
5846 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5847 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005848 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005849 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005850 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005851 return ExprError();
5852
5853 case OR_Deleted:
5854 Diag(OpLoc, diag::err_ovl_deleted_oper)
5855 << Best->Function->isDeleted()
5856 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005857 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005858 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005859 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005860 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005861
Douglas Gregor66950a32009-09-30 21:46:01 +00005862 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005863 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005864}
5865
Sebastian Redladba46e2009-10-29 20:17:01 +00005866Action::OwningExprResult
5867Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5868 SourceLocation RLoc,
5869 ExprArg Base, ExprArg Idx) {
5870 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5871 static_cast<Expr*>(Idx.get()) };
5872 DeclarationName OpName =
5873 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5874
5875 // If either side is type-dependent, create an appropriate dependent
5876 // expression.
5877 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5878
John McCall58cc69d2010-01-27 01:50:18 +00005879 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005880 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005881 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005882 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005883 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005884 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005885
5886 Base.release();
5887 Idx.release();
5888 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5889 Args, 2,
5890 Context.DependentTy,
5891 RLoc));
5892 }
5893
5894 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005895 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005896
5897 // Subscript can only be overloaded as a member function.
5898
5899 // Add operator candidates that are member functions.
5900 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5901
5902 // Add builtin operator candidates.
5903 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5904
5905 // Perform overload resolution.
5906 OverloadCandidateSet::iterator Best;
5907 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5908 case OR_Success: {
5909 // We found a built-in operator or an overloaded operator.
5910 FunctionDecl *FnDecl = Best->Function;
5911
5912 if (FnDecl) {
5913 // We matched an overloaded operator. Build a call to that
5914 // operator.
5915
John McCallb3a44002010-01-28 01:42:12 +00005916 CheckMemberOperatorAccess(LLoc, Args[0], FnDecl, Best->getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005917
Sebastian Redladba46e2009-10-29 20:17:01 +00005918 // Convert the arguments.
5919 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Anders Carlssona68e51e2010-01-29 18:37:50 +00005920 if (PerformObjectArgumentInitialization(Args[0], Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00005921 return ExprError();
5922
Anders Carlssona68e51e2010-01-29 18:37:50 +00005923 // Convert the arguments.
5924 OwningExprResult InputInit
5925 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5926 FnDecl->getParamDecl(0)),
5927 SourceLocation(),
5928 Owned(Args[1]));
5929 if (InputInit.isInvalid())
5930 return ExprError();
5931
5932 Args[1] = InputInit.takeAs<Expr>();
5933
Sebastian Redladba46e2009-10-29 20:17:01 +00005934 // Determine the result type
5935 QualType ResultTy
5936 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5937 ResultTy = ResultTy.getNonReferenceType();
5938
5939 // Build the actual expression node.
5940 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5941 LLoc);
5942 UsualUnaryConversions(FnExpr);
5943
5944 Base.release();
5945 Idx.release();
5946 ExprOwningPtr<CXXOperatorCallExpr>
5947 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5948 FnExpr, Args, 2,
5949 ResultTy, RLoc));
5950
5951 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5952 FnDecl))
5953 return ExprError();
5954
5955 return MaybeBindToTemporary(TheCall.release());
5956 } else {
5957 // We matched a built-in operator. Convert the arguments, then
5958 // break out so that we will build the appropriate built-in
5959 // operator node.
5960 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005961 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005962 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005963 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005964 return ExprError();
5965
5966 break;
5967 }
5968 }
5969
5970 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005971 if (CandidateSet.empty())
5972 Diag(LLoc, diag::err_ovl_no_oper)
5973 << Args[0]->getType() << /*subscript*/ 0
5974 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5975 else
5976 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5977 << Args[0]->getType()
5978 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005979 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005980 "[]", LLoc);
5981 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005982 }
5983
5984 case OR_Ambiguous:
5985 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5986 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005987 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005988 "[]", LLoc);
5989 return ExprError();
5990
5991 case OR_Deleted:
5992 Diag(LLoc, diag::err_ovl_deleted_oper)
5993 << Best->Function->isDeleted() << "[]"
5994 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005995 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005996 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005997 return ExprError();
5998 }
5999
6000 // We matched a built-in operator; build it.
6001 Base.release();
6002 Idx.release();
6003 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6004 Owned(Args[1]), RLoc);
6005}
6006
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006007/// BuildCallToMemberFunction - Build a call to a member
6008/// function. MemExpr is the expression that refers to the member
6009/// function (and includes the object parameter), Args/NumArgs are the
6010/// arguments to the function call (not including the object
6011/// parameter). The caller needs to validate that the member
6012/// expression refers to a member function or an overloaded member
6013/// function.
John McCall2d74de92009-12-01 22:10:20 +00006014Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006015Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6016 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006017 unsigned NumArgs, SourceLocation *CommaLocs,
6018 SourceLocation RParenLoc) {
6019 // Dig out the member expression. This holds both the object
6020 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006021 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6022
John McCall10eae182009-11-30 22:42:35 +00006023 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006024 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00006025 if (isa<MemberExpr>(NakedMemExpr)) {
6026 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006027 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
6028 } else {
6029 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00006030
John McCall6e9f8f62009-12-03 04:06:58 +00006031 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006032
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006033 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006034 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006035
John McCall2d74de92009-12-01 22:10:20 +00006036 // FIXME: avoid copy.
6037 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6038 if (UnresExpr->hasExplicitTemplateArgs()) {
6039 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6040 TemplateArgs = &TemplateArgsBuffer;
6041 }
6042
John McCall10eae182009-11-30 22:42:35 +00006043 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6044 E = UnresExpr->decls_end(); I != E; ++I) {
6045
John McCall6e9f8f62009-12-03 04:06:58 +00006046 NamedDecl *Func = *I;
6047 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6048 if (isa<UsingShadowDecl>(Func))
6049 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6050
John McCall10eae182009-11-30 22:42:35 +00006051 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006052 // If explicit template arguments were provided, we can't call a
6053 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006054 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006055 continue;
6056
John McCallb89836b2010-01-26 01:37:31 +00006057 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
6058 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006059 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006060 } else {
John McCall10eae182009-11-30 22:42:35 +00006061 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCallb89836b2010-01-26 01:37:31 +00006062 I.getAccess(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006063 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006064 CandidateSet,
6065 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006066 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006067 }
Mike Stump11289f42009-09-09 15:08:12 +00006068
John McCall10eae182009-11-30 22:42:35 +00006069 DeclarationName DeclName = UnresExpr->getMemberName();
6070
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006071 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006072 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006073 case OR_Success:
6074 Method = cast<CXXMethodDecl>(Best->Function);
John McCall58cc69d2010-01-27 01:50:18 +00006075 CheckUnresolvedMemberAccess(UnresExpr, Method, Best->getAccess());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006076 break;
6077
6078 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006079 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006080 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006081 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006082 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006083 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006084 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006085
6086 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006087 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006088 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006089 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006090 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006091 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006092
6093 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006094 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006095 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006096 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006097 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006098 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006099 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006100 }
6101
Douglas Gregor51c538b2009-11-20 19:42:02 +00006102 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00006103
John McCall2d74de92009-12-01 22:10:20 +00006104 // If overload resolution picked a static member, build a
6105 // non-member call based on that function.
6106 if (Method->isStatic()) {
6107 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6108 Args, NumArgs, RParenLoc);
6109 }
6110
John McCall10eae182009-11-30 22:42:35 +00006111 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006112 }
6113
6114 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006115 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006116 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006117 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006118 Method->getResultType().getNonReferenceType(),
6119 RParenLoc));
6120
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006121 // Check for a valid return type.
6122 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6123 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006124 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006125
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006126 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00006127 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006128 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006129 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00006130 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006131 MemExpr->setBase(ObjectArg);
6132
6133 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006134 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006135 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006136 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006137 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006138
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006139 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006140 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006141
John McCall2d74de92009-12-01 22:10:20 +00006142 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006143}
6144
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006145/// BuildCallToObjectOfClassType - Build a call to an object of class
6146/// type (C++ [over.call.object]), which can end up invoking an
6147/// overloaded function call operator (@c operator()) or performing a
6148/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006149Sema::ExprResult
6150Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006151 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006152 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006153 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006154 SourceLocation RParenLoc) {
6155 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006156 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006157
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006158 // C++ [over.call.object]p1:
6159 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006160 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006161 // candidate functions includes at least the function call
6162 // operators of T. The function call operators of T are obtained by
6163 // ordinary lookup of the name operator() in the context of
6164 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006165 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006166 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006167
6168 if (RequireCompleteType(LParenLoc, Object->getType(),
6169 PartialDiagnostic(diag::err_incomplete_object_call)
6170 << Object->getSourceRange()))
6171 return true;
6172
John McCall27b18f82009-11-17 02:14:36 +00006173 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6174 LookupQualifiedName(R, Record->getDecl());
6175 R.suppressDiagnostics();
6176
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006177 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006178 Oper != OperEnd; ++Oper) {
John McCallb89836b2010-01-26 01:37:31 +00006179 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6180 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006181 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006182 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006183
Douglas Gregorab7897a2008-11-19 22:57:39 +00006184 // C++ [over.call.object]p2:
6185 // In addition, for each conversion function declared in T of the
6186 // form
6187 //
6188 // operator conversion-type-id () cv-qualifier;
6189 //
6190 // where cv-qualifier is the same cv-qualification as, or a
6191 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006192 // denotes the type "pointer to function of (P1,...,Pn) returning
6193 // R", or the type "reference to pointer to function of
6194 // (P1,...,Pn) returning R", or the type "reference to function
6195 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006196 // is also considered as a candidate function. Similarly,
6197 // surrogate call functions are added to the set of candidate
6198 // functions for each conversion function declared in an
6199 // accessible base class provided the function is not hidden
6200 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006201 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006202 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006203 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006204 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006205 NamedDecl *D = *I;
6206 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6207 if (isa<UsingShadowDecl>(D))
6208 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6209
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006210 // Skip over templated conversion functions; they aren't
6211 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006212 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006213 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006214
John McCall6e9f8f62009-12-03 04:06:58 +00006215 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006216
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006217 // Strip the reference type (if any) and then the pointer type (if
6218 // any) to get down to what might be a function type.
6219 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6220 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6221 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006222
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006223 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCallb89836b2010-01-26 01:37:31 +00006224 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006225 Object->getType(), Args, NumArgs,
6226 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006227 }
Mike Stump11289f42009-09-09 15:08:12 +00006228
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006229 // Perform overload resolution.
6230 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006231 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006232 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006233 // Overload resolution succeeded; we'll build the appropriate call
6234 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006235 break;
6236
6237 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006238 if (CandidateSet.empty())
6239 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6240 << Object->getType() << /*call*/ 1
6241 << Object->getSourceRange();
6242 else
6243 Diag(Object->getSourceRange().getBegin(),
6244 diag::err_ovl_no_viable_object_call)
6245 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006246 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006247 break;
6248
6249 case OR_Ambiguous:
6250 Diag(Object->getSourceRange().getBegin(),
6251 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006252 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006253 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006254 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006255
6256 case OR_Deleted:
6257 Diag(Object->getSourceRange().getBegin(),
6258 diag::err_ovl_deleted_object_call)
6259 << Best->Function->isDeleted()
6260 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006261 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006262 break;
Mike Stump11289f42009-09-09 15:08:12 +00006263 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006264
Douglas Gregorab7897a2008-11-19 22:57:39 +00006265 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006266 // We had an error; delete all of the subexpressions and return
6267 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006268 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006269 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006270 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006271 return true;
6272 }
6273
Douglas Gregorab7897a2008-11-19 22:57:39 +00006274 if (Best->Function == 0) {
6275 // Since there is no function declaration, this is one of the
6276 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006277 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006278 = cast<CXXConversionDecl>(
6279 Best->Conversions[0].UserDefined.ConversionFunction);
6280
John McCall2cb94162010-01-28 07:38:46 +00006281 CheckMemberOperatorAccess(LParenLoc, Object, Conv, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006282
Douglas Gregorab7897a2008-11-19 22:57:39 +00006283 // We selected one of the surrogate functions that converts the
6284 // object parameter to a function pointer. Perform the conversion
6285 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006286
6287 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006288 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006289 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006290
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006291 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006292 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6293 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006294 }
6295
John McCall2cb94162010-01-28 07:38:46 +00006296 CheckMemberOperatorAccess(LParenLoc, Object,
6297 Best->Function, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006298
Douglas Gregorab7897a2008-11-19 22:57:39 +00006299 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6300 // that calls this method, using Object for the implicit object
6301 // parameter and passing along the remaining arguments.
6302 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006303 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006304
6305 unsigned NumArgsInProto = Proto->getNumArgs();
6306 unsigned NumArgsToCheck = NumArgs;
6307
6308 // Build the full argument list for the method call (the
6309 // implicit object parameter is placed at the beginning of the
6310 // list).
6311 Expr **MethodArgs;
6312 if (NumArgs < NumArgsInProto) {
6313 NumArgsToCheck = NumArgsInProto;
6314 MethodArgs = new Expr*[NumArgsInProto + 1];
6315 } else {
6316 MethodArgs = new Expr*[NumArgs + 1];
6317 }
6318 MethodArgs[0] = Object;
6319 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6320 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006321
6322 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006323 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006324 UsualUnaryConversions(NewFn);
6325
6326 // Once we've built TheCall, all of the expressions are properly
6327 // owned.
6328 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006329 ExprOwningPtr<CXXOperatorCallExpr>
6330 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006331 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006332 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006333 delete [] MethodArgs;
6334
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006335 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6336 Method))
6337 return true;
6338
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006339 // We may have default arguments. If so, we need to allocate more
6340 // slots in the call for them.
6341 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006342 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006343 else if (NumArgs > NumArgsInProto)
6344 NumArgsToCheck = NumArgsInProto;
6345
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006346 bool IsError = false;
6347
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006348 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006349 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006350 TheCall->setArg(0, Object);
6351
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006352
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006353 // Check the argument types.
6354 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006355 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006356 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006357 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006358
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006359 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006360
6361 OwningExprResult InputInit
6362 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6363 Method->getParamDecl(i)),
6364 SourceLocation(), Owned(Arg));
6365
6366 IsError |= InputInit.isInvalid();
6367 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006368 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006369 OwningExprResult DefArg
6370 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6371 if (DefArg.isInvalid()) {
6372 IsError = true;
6373 break;
6374 }
6375
6376 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006377 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006378
6379 TheCall->setArg(i + 1, Arg);
6380 }
6381
6382 // If this is a variadic call, handle args passed through "...".
6383 if (Proto->isVariadic()) {
6384 // Promote the arguments (C99 6.5.2.2p7).
6385 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6386 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006387 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006388 TheCall->setArg(i + 1, Arg);
6389 }
6390 }
6391
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006392 if (IsError) return true;
6393
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006394 if (CheckFunctionCall(Method, TheCall.get()))
6395 return true;
6396
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006397 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006398}
6399
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006400/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006401/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006402/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006403Sema::OwningExprResult
6404Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6405 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006406 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006407
John McCallbc077cf2010-02-08 23:07:23 +00006408 SourceLocation Loc = Base->getExprLoc();
6409
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006410 // C++ [over.ref]p1:
6411 //
6412 // [...] An expression x->m is interpreted as (x.operator->())->m
6413 // for a class object x of type T if T::operator->() exists and if
6414 // the operator is selected as the best match function by the
6415 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006416 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006417 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006418 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006419
John McCallbc077cf2010-02-08 23:07:23 +00006420 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006421 PDiag(diag::err_typecheck_incomplete_tag)
6422 << Base->getSourceRange()))
6423 return ExprError();
6424
John McCall27b18f82009-11-17 02:14:36 +00006425 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6426 LookupQualifiedName(R, BaseRecord->getDecl());
6427 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006428
6429 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006430 Oper != OperEnd; ++Oper) {
6431 NamedDecl *D = *Oper;
6432 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6433 if (isa<UsingShadowDecl>(D))
6434 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6435
John McCallb89836b2010-01-26 01:37:31 +00006436 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00006437 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006438 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006439 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006440
6441 // Perform overload resolution.
6442 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006443 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006444 case OR_Success:
6445 // Overload resolution succeeded; we'll build the call below.
6446 break;
6447
6448 case OR_No_Viable_Function:
6449 if (CandidateSet.empty())
6450 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006451 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006452 else
6453 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006454 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006455 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006456 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006457
6458 case OR_Ambiguous:
6459 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006460 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006461 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006462 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006463
6464 case OR_Deleted:
6465 Diag(OpLoc, diag::err_ovl_deleted_oper)
6466 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006467 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006468 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006469 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006470 }
6471
6472 // Convert the object parameter.
6473 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006474 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006475 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006476
6477 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006478 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006479
6480 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006481 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6482 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006483 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006484
6485 QualType ResultTy = Method->getResultType().getNonReferenceType();
6486 ExprOwningPtr<CXXOperatorCallExpr>
6487 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6488 &Base, 1, ResultTy, OpLoc));
6489
6490 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6491 Method))
6492 return ExprError();
6493 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006494}
6495
Douglas Gregorcd695e52008-11-10 20:40:00 +00006496/// FixOverloadedFunctionReference - E is an expression that refers to
6497/// a C++ overloaded function (possibly with some parentheses and
6498/// perhaps a '&' around it). We have resolved the overloaded function
6499/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006500/// refer (possibly indirectly) to Fn. Returns the new expr.
6501Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006502 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006503 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6504 if (SubExpr == PE->getSubExpr())
6505 return PE->Retain();
6506
6507 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6508 }
6509
6510 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6511 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006512 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006513 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006514 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006515 if (SubExpr == ICE->getSubExpr())
6516 return ICE->Retain();
6517
6518 return new (Context) ImplicitCastExpr(ICE->getType(),
6519 ICE->getCastKind(),
6520 SubExpr,
6521 ICE->isLvalueCast());
6522 }
6523
6524 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006525 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006526 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006527 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6528 if (Method->isStatic()) {
6529 // Do nothing: static member functions aren't any different
6530 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006531 } else {
John McCalle66edc12009-11-24 19:00:30 +00006532 // Fix the sub expression, which really has to be an
6533 // UnresolvedLookupExpr holding an overloaded member function
6534 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006535 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6536 if (SubExpr == UnOp->getSubExpr())
6537 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006538
John McCalld14a8642009-11-21 08:51:07 +00006539 assert(isa<DeclRefExpr>(SubExpr)
6540 && "fixed to something other than a decl ref");
6541 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6542 && "fixed to a member ref with no nested name qualifier");
6543
6544 // We have taken the address of a pointer to member
6545 // function. Perform the computation here so that we get the
6546 // appropriate pointer to member type.
6547 QualType ClassType
6548 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6549 QualType MemPtrType
6550 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6551
6552 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6553 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006554 }
6555 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006556 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6557 if (SubExpr == UnOp->getSubExpr())
6558 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006559
Douglas Gregor51c538b2009-11-20 19:42:02 +00006560 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6561 Context.getPointerType(SubExpr->getType()),
6562 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006563 }
John McCalld14a8642009-11-21 08:51:07 +00006564
6565 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006566 // FIXME: avoid copy.
6567 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006568 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006569 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6570 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006571 }
6572
John McCalld14a8642009-11-21 08:51:07 +00006573 return DeclRefExpr::Create(Context,
6574 ULE->getQualifier(),
6575 ULE->getQualifierRange(),
6576 Fn,
6577 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006578 Fn->getType(),
6579 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006580 }
6581
John McCall10eae182009-11-30 22:42:35 +00006582 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006583 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006584 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6585 if (MemExpr->hasExplicitTemplateArgs()) {
6586 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6587 TemplateArgs = &TemplateArgsBuffer;
6588 }
John McCall6b51f282009-11-23 01:53:49 +00006589
John McCall2d74de92009-12-01 22:10:20 +00006590 Expr *Base;
6591
6592 // If we're filling in
6593 if (MemExpr->isImplicitAccess()) {
6594 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6595 return DeclRefExpr::Create(Context,
6596 MemExpr->getQualifier(),
6597 MemExpr->getQualifierRange(),
6598 Fn,
6599 MemExpr->getMemberLoc(),
6600 Fn->getType(),
6601 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006602 } else {
6603 SourceLocation Loc = MemExpr->getMemberLoc();
6604 if (MemExpr->getQualifier())
6605 Loc = MemExpr->getQualifierRange().getBegin();
6606 Base = new (Context) CXXThisExpr(Loc,
6607 MemExpr->getBaseType(),
6608 /*isImplicit=*/true);
6609 }
John McCall2d74de92009-12-01 22:10:20 +00006610 } else
6611 Base = MemExpr->getBase()->Retain();
6612
6613 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006614 MemExpr->isArrow(),
6615 MemExpr->getQualifier(),
6616 MemExpr->getQualifierRange(),
6617 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006618 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006619 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006620 Fn->getType());
6621 }
6622
Douglas Gregor51c538b2009-11-20 19:42:02 +00006623 assert(false && "Invalid reference to overloaded function");
6624 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006625}
6626
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006627Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6628 FunctionDecl *Fn) {
6629 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6630}
6631
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006632} // end namespace clang