blob: 7a37daaa742871b94a2ef30f6b3676b8f1308e7c [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000229 OS << '\'' << ConversionFunction << '\'';
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.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000439ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000440Sema::TryImplicitConversion(Expr* From, QualType ToType,
441 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000442 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000443 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000444 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000445 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000446 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000447 return ICS;
448 }
449
450 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000451 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000452 return ICS;
453 }
454
Douglas Gregor5ab11652010-04-17 22:01:05 +0000455 if (SuppressUserConversions) {
456 // C++ [over.ics.user]p4:
457 // A conversion of an expression of class type to the same class
458 // type is given Exact Match rank, and a conversion of an
459 // expression of class type to a base class of that type is
460 // given Conversion rank, in spite of the fact that a copy/move
461 // constructor (i.e., a user-defined conversion function) is
462 // called for those cases.
463 QualType FromType = From->getType();
464 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
465 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
466 IsDerivedFrom(FromType, ToType))) {
467 // We're not in the case above, so there is no conversion that
468 // we can perform.
469 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
470 return ICS;
471 }
472
473 ICS.setStandard();
474 ICS.Standard.setAsIdentityConversion();
475 ICS.Standard.setFromType(FromType);
476 ICS.Standard.setAllToTypes(ToType);
477
478 // We don't actually check at this point whether there is a valid
479 // copy/move constructor, since overloading just assumes that it
480 // exists. When we actually perform initialization, we'll find the
481 // appropriate constructor to copy the returned object, if needed.
482 ICS.Standard.CopyConstructor = 0;
483
484 // Determine whether this is considered a derived-to-base conversion.
485 if (!Context.hasSameUnqualifiedType(FromType, ToType))
486 ICS.Standard.Second = ICK_Derived_To_Base;
487
488 return ICS;
489 }
490
491 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000492 OverloadCandidateSet Conversions(From->getExprLoc());
493 OverloadingResult UserDefResult
494 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000495 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000496
497 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000498 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000499 // C++ [over.ics.user]p4:
500 // A conversion of an expression of class type to the same class
501 // type is given Exact Match rank, and a conversion of an
502 // expression of class type to a base class of that type is
503 // given Conversion rank, in spite of the fact that a copy
504 // constructor (i.e., a user-defined conversion function) is
505 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000506 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000507 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000508 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000509 = Context.getCanonicalType(From->getType().getUnqualifiedType());
510 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000511 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000512 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000513 // Turn this into a "standard" conversion sequence, so that it
514 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000515 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000516 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000517 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000518 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000519 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000520 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000521 ICS.Standard.Second = ICK_Derived_To_Base;
522 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000523 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000524
525 // C++ [over.best.ics]p4:
526 // However, when considering the argument of a user-defined
527 // conversion function that is a candidate by 13.3.1.3 when
528 // invoked for the copying of the temporary in the second step
529 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
530 // 13.3.1.6 in all cases, only standard conversion sequences and
531 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000532 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000533 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000534 }
John McCalle8c8cd22010-01-13 22:30:33 +0000535 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000536 ICS.setAmbiguous();
537 ICS.Ambiguous.setFromType(From->getType());
538 ICS.Ambiguous.setToType(ToType);
539 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
540 Cand != Conversions.end(); ++Cand)
541 if (Cand->Viable)
542 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000543 } else {
John McCall65eb8792010-02-25 01:37:24 +0000544 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000545 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000546
547 return ICS;
548}
549
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000550/// PerformImplicitConversion - Perform an implicit conversion of the
551/// expression From to the type ToType. Returns true if there was an
552/// error, false otherwise. The expression From is replaced with the
553/// converted expression. Flavor is the kind of conversion we're
554/// performing, used in the error message. If @p AllowExplicit,
555/// explicit user-defined conversions are permitted.
556bool
557Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
558 AssignmentAction Action, bool AllowExplicit) {
559 ImplicitConversionSequence ICS;
560 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
561}
562
563bool
564Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
565 AssignmentAction Action, bool AllowExplicit,
566 ImplicitConversionSequence& ICS) {
567 ICS = TryImplicitConversion(From, ToType,
568 /*SuppressUserConversions=*/false,
569 AllowExplicit,
570 /*InOverloadResolution=*/false);
571 return PerformImplicitConversion(From, ToType, ICS, Action);
572}
573
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000574/// \brief Determine whether the conversion from FromType to ToType is a valid
575/// conversion that strips "noreturn" off the nested function type.
576static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
577 QualType ToType, QualType &ResultTy) {
578 if (Context.hasSameUnqualifiedType(FromType, ToType))
579 return false;
580
581 // Strip the noreturn off the type we're converting from; noreturn can
582 // safely be removed.
583 FromType = Context.getNoReturnType(FromType, false);
584 if (!Context.hasSameUnqualifiedType(FromType, ToType))
585 return false;
586
587 ResultTy = FromType;
588 return true;
589}
590
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000591/// IsStandardConversion - Determines whether there is a standard
592/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
593/// expression From to the type ToType. Standard conversion sequences
594/// only consider non-class types; for conversions that involve class
595/// types, use TryImplicitConversion. If a conversion exists, SCS will
596/// contain the standard conversion sequence required to perform this
597/// conversion and this routine will return true. Otherwise, this
598/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000599bool
600Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000601 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000602 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603 QualType FromType = From->getType();
604
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000605 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000606 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000607 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000608 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000609 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000610 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000611
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000612 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000613 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000614 if (FromType->isRecordType() || ToType->isRecordType()) {
615 if (getLangOptions().CPlusPlus)
616 return false;
617
Mike Stump11289f42009-09-09 15:08:12 +0000618 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000619 }
620
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000621 // The first conversion can be an lvalue-to-rvalue conversion,
622 // array-to-pointer conversion, or function-to-pointer conversion
623 // (C++ 4p1).
624
John McCall16df1e52010-03-30 21:47:33 +0000625 DeclAccessPair AccessPair;
626
Mike Stump11289f42009-09-09 15:08:12 +0000627 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000628 // An lvalue (3.10) of a non-function, non-array type T can be
629 // converted to an rvalue.
630 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000631 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000632 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000633 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000634 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000635
636 // If T is a non-class type, the type of the rvalue is the
637 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000638 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
639 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000640 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000641 } else if (FromType->isArrayType()) {
642 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000643 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000644
645 // An lvalue or rvalue of type "array of N T" or "array of unknown
646 // bound of T" can be converted to an rvalue of type "pointer to
647 // T" (C++ 4.2p1).
648 FromType = Context.getArrayDecayedType(FromType);
649
650 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
651 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000652 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653
654 // For the purpose of ranking in overload resolution
655 // (13.3.3.1.1), this conversion is considered an
656 // array-to-pointer conversion followed by a qualification
657 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000658 SCS.Second = ICK_Identity;
659 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000660 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000662 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000663 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
664 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000665 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000666
667 // An lvalue of function type T can be converted to an rvalue of
668 // type "pointer to T." The result is a pointer to the
669 // function. (C++ 4.3p1).
670 FromType = Context.getPointerType(FromType);
Douglas Gregor064fdb22010-04-14 23:11:21 +0000671 } else if (From->getType() == Context.OverloadTy) {
672 if (FunctionDecl *Fn
673 = ResolveAddressOfOverloadedFunction(From, ToType, false,
674 AccessPair)) {
675 // Address of overloaded function (C++ [over.over]).
676 SCS.First = ICK_Function_To_Pointer;
Douglas Gregorcd695e52008-11-10 20:40:00 +0000677
Douglas Gregor064fdb22010-04-14 23:11:21 +0000678 // We were able to resolve the address of the overloaded function,
679 // so we can convert to the type of that function.
680 FromType = Fn->getType();
681 if (ToType->isLValueReferenceType())
682 FromType = Context.getLValueReferenceType(FromType);
683 else if (ToType->isRValueReferenceType())
684 FromType = Context.getRValueReferenceType(FromType);
685 else if (ToType->isMemberPointerType()) {
686 // Resolve address only succeeds if both sides are member pointers,
687 // but it doesn't have to be the same class. See DR 247.
688 // Note that this means that the type of &Derived::fn can be
689 // Ret (Base::*)(Args) if the fn overload actually found is from the
690 // base class, even if it was brought into the derived class via a
691 // using declaration. The standard isn't clear on this issue at all.
692 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
693 FromType = Context.getMemberPointerType(FromType,
694 Context.getTypeDeclType(M->getParent()).getTypePtr());
695 } else {
696 FromType = Context.getPointerType(FromType);
697 }
698 } else {
699 return false;
700 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000701 } else {
702 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000703 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000704 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000705 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000706
707 // The second conversion can be an integral promotion, floating
708 // point promotion, integral conversion, floating point conversion,
709 // floating-integral conversion, pointer conversion,
710 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000711 // For overloading in C, this can also be a "compatible-type"
712 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000713 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000714 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000715 // The unqualified versions of the types are the same: there's no
716 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000717 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000718 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000719 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000720 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000721 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000722 } else if (IsFloatingPointPromotion(FromType, ToType)) {
723 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000724 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000726 } else if (IsComplexPromotion(FromType, ToType)) {
727 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000728 SCS.Second = ICK_Complex_Promotion;
729 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000730 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000731 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000732 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000733 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000734 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000735 } else if (FromType->isComplexType() && ToType->isComplexType()) {
736 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000737 SCS.Second = ICK_Complex_Conversion;
738 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000739 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
740 (ToType->isComplexType() && FromType->isArithmeticType())) {
741 // Complex-real conversions (C99 6.3.1.7)
742 SCS.Second = ICK_Complex_Real;
743 FromType = ToType.getUnqualifiedType();
744 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
745 // Floating point conversions (C++ 4.8).
746 SCS.Second = ICK_Floating_Conversion;
747 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000748 } else if ((FromType->isFloatingType() &&
749 ToType->isIntegralType() && (!ToType->isBooleanType() &&
750 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000751 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000752 ToType->isFloatingType())) {
753 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000754 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000755 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000756 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
757 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000758 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000759 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000760 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000761 } else if (IsMemberPointerConversion(From, FromType, ToType,
762 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000763 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000764 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000765 } else if (ToType->isBooleanType() &&
766 (FromType->isArithmeticType() ||
767 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000768 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000769 FromType->isBlockPointerType() ||
770 FromType->isMemberPointerType() ||
771 FromType->isNullPtrType())) {
772 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000773 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000774 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000775 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000776 Context.typesAreCompatible(ToType, FromType)) {
777 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000778 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000779 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
780 // Treat a conversion that strips "noreturn" as an identity conversion.
781 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000782 } else {
783 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000784 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000785 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000786 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000788 QualType CanonFrom;
789 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000790 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000791 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000792 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000793 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000794 CanonFrom = Context.getCanonicalType(FromType);
795 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000796 } else {
797 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000798 SCS.Third = ICK_Identity;
799
Mike Stump11289f42009-09-09 15:08:12 +0000800 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000801 // [...] Any difference in top-level cv-qualification is
802 // subsumed by the initialization itself and does not constitute
803 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000804 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000805 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000806 if (CanonFrom.getLocalUnqualifiedType()
807 == CanonTo.getLocalUnqualifiedType() &&
808 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000809 FromType = ToType;
810 CanonFrom = CanonTo;
811 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000812 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000813 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000814
815 // If we have not converted the argument type to the parameter type,
816 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000817 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000818 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000819
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000820 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000821}
822
823/// IsIntegralPromotion - Determines whether the conversion from the
824/// expression From (whose potentially-adjusted type is FromType) to
825/// ToType is an integral promotion (C++ 4.5). If so, returns true and
826/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000827bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000828 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000829 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000830 if (!To) {
831 return false;
832 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000833
834 // An rvalue of type char, signed char, unsigned char, short int, or
835 // unsigned short int can be converted to an rvalue of type int if
836 // int can represent all the values of the source type; otherwise,
837 // the source rvalue can be converted to an rvalue of type unsigned
838 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000839 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
840 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000841 if (// We can promote any signed, promotable integer type to an int
842 (FromType->isSignedIntegerType() ||
843 // We can promote any unsigned integer type whose size is
844 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000845 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000846 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000848 }
849
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000850 return To->getKind() == BuiltinType::UInt;
851 }
852
853 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
854 // can be converted to an rvalue of the first of the following types
855 // that can represent all the values of its underlying type: int,
856 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000857
858 // We pre-calculate the promotion type for enum types.
859 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
860 if (ToType->isIntegerType())
861 return Context.hasSameUnqualifiedType(ToType,
862 FromEnumType->getDecl()->getPromotionType());
863
864 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000865 // Determine whether the type we're converting from is signed or
866 // unsigned.
867 bool FromIsSigned;
868 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000869
870 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
871 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872
873 // The types we'll try to promote to, in the appropriate
874 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000875 QualType PromoteTypes[6] = {
876 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000877 Context.LongTy, Context.UnsignedLongTy ,
878 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000879 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000880 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000881 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
882 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000883 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000884 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
885 // We found the type that we can promote to. If this is the
886 // type we wanted, we have a promotion. Otherwise, no
887 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000888 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889 }
890 }
891 }
892
893 // An rvalue for an integral bit-field (9.6) can be converted to an
894 // rvalue of type int if int can represent all the values of the
895 // bit-field; otherwise, it can be converted to unsigned int if
896 // unsigned int can represent all the values of the bit-field. If
897 // the bit-field is larger yet, no integral promotion applies to
898 // it. If the bit-field has an enumerated type, it is treated as any
899 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000900 // FIXME: We should delay checking of bit-fields until we actually perform the
901 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000902 using llvm::APSInt;
903 if (From)
904 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000905 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000906 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
907 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
908 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
909 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000910
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000911 // Are we promoting to an int from a bitfield that fits in an int?
912 if (BitWidth < ToSize ||
913 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
914 return To->getKind() == BuiltinType::Int;
915 }
Mike Stump11289f42009-09-09 15:08:12 +0000916
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000917 // Are we promoting to an unsigned int from an unsigned bitfield
918 // that fits into an unsigned int?
919 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
920 return To->getKind() == BuiltinType::UInt;
921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000923 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000924 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000925 }
Mike Stump11289f42009-09-09 15:08:12 +0000926
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000927 // An rvalue of type bool can be converted to an rvalue of type int,
928 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000929 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000930 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000931 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000932
933 return false;
934}
935
936/// IsFloatingPointPromotion - Determines whether the conversion from
937/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
938/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000939bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000940 /// An rvalue of type float can be converted to an rvalue of type
941 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000942 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
943 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000944 if (FromBuiltin->getKind() == BuiltinType::Float &&
945 ToBuiltin->getKind() == BuiltinType::Double)
946 return true;
947
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000948 // C99 6.3.1.5p1:
949 // When a float is promoted to double or long double, or a
950 // double is promoted to long double [...].
951 if (!getLangOptions().CPlusPlus &&
952 (FromBuiltin->getKind() == BuiltinType::Float ||
953 FromBuiltin->getKind() == BuiltinType::Double) &&
954 (ToBuiltin->getKind() == BuiltinType::LongDouble))
955 return true;
956 }
957
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000958 return false;
959}
960
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000961/// \brief Determine if a conversion is a complex promotion.
962///
963/// A complex promotion is defined as a complex -> complex conversion
964/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000965/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000966bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000967 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000968 if (!FromComplex)
969 return false;
970
John McCall9dd450b2009-09-21 23:43:11 +0000971 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000972 if (!ToComplex)
973 return false;
974
975 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000976 ToComplex->getElementType()) ||
977 IsIntegralPromotion(0, FromComplex->getElementType(),
978 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000979}
980
Douglas Gregor237f96c2008-11-26 23:31:11 +0000981/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
982/// the pointer type FromPtr to a pointer to type ToPointee, with the
983/// same type qualifiers as FromPtr has on its pointee type. ToType,
984/// if non-empty, will be a pointer to ToType that may or may not have
985/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000986static QualType
987BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000988 QualType ToPointee, QualType ToType,
989 ASTContext &Context) {
990 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
991 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000992 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000993
994 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000995 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000996 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000997 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000998 return ToType;
999
1000 // Build a pointer to ToPointee. It has the right qualifiers
1001 // already.
1002 return Context.getPointerType(ToPointee);
1003 }
1004
1005 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001006 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001007 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1008 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001009}
1010
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001011/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1012/// the FromType, which is an objective-c pointer, to ToType, which may or may
1013/// not have the right set of qualifiers.
1014static QualType
1015BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1016 QualType ToType,
1017 ASTContext &Context) {
1018 QualType CanonFromType = Context.getCanonicalType(FromType);
1019 QualType CanonToType = Context.getCanonicalType(ToType);
1020 Qualifiers Quals = CanonFromType.getQualifiers();
1021
1022 // Exact qualifier match -> return the pointer type we're converting to.
1023 if (CanonToType.getLocalQualifiers() == Quals)
1024 return ToType;
1025
1026 // Just build a canonical type that has the right qualifiers.
1027 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1028}
1029
Mike Stump11289f42009-09-09 15:08:12 +00001030static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001031 bool InOverloadResolution,
1032 ASTContext &Context) {
1033 // Handle value-dependent integral null pointer constants correctly.
1034 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1035 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1036 Expr->getType()->isIntegralType())
1037 return !InOverloadResolution;
1038
Douglas Gregor56751b52009-09-25 04:25:58 +00001039 return Expr->isNullPointerConstant(Context,
1040 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1041 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001042}
Mike Stump11289f42009-09-09 15:08:12 +00001043
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001044/// IsPointerConversion - Determines whether the conversion of the
1045/// expression From, which has the (possibly adjusted) type FromType,
1046/// can be converted to the type ToType via a pointer conversion (C++
1047/// 4.10). If so, returns true and places the converted type (that
1048/// might differ from ToType in its cv-qualifiers at some level) into
1049/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001050///
Douglas Gregora29dc052008-11-27 01:19:21 +00001051/// This routine also supports conversions to and from block pointers
1052/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1053/// pointers to interfaces. FIXME: Once we've determined the
1054/// appropriate overloading rules for Objective-C, we may want to
1055/// split the Objective-C checks into a different routine; however,
1056/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001057/// conversions, so for now they live here. IncompatibleObjC will be
1058/// set if the conversion is an allowed Objective-C conversion that
1059/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001060bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001061 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001062 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001063 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001064 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001065 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1066 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001067
Mike Stump11289f42009-09-09 15:08:12 +00001068 // Conversion from a null pointer constant to any Objective-C pointer type.
1069 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001070 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001071 ConvertedType = ToType;
1072 return true;
1073 }
1074
Douglas Gregor231d1c62008-11-27 00:15:41 +00001075 // Blocks: Block pointers can be converted to void*.
1076 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001077 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001078 ConvertedType = ToType;
1079 return true;
1080 }
1081 // Blocks: A null pointer constant can be converted to a block
1082 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001083 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001084 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001085 ConvertedType = ToType;
1086 return true;
1087 }
1088
Sebastian Redl576fd422009-05-10 18:38:11 +00001089 // If the left-hand-side is nullptr_t, the right side can be a null
1090 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001091 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001092 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001093 ConvertedType = ToType;
1094 return true;
1095 }
1096
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001097 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001098 if (!ToTypePtr)
1099 return false;
1100
1101 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001102 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103 ConvertedType = ToType;
1104 return true;
1105 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001106
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001107 // Beyond this point, both types need to be pointers
1108 // , including objective-c pointers.
1109 QualType ToPointeeType = ToTypePtr->getPointeeType();
1110 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1111 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1112 ToType, Context);
1113 return true;
1114
1115 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001116 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001117 if (!FromTypePtr)
1118 return false;
1119
1120 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001121
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122 // An rvalue of type "pointer to cv T," where T is an object type,
1123 // can be converted to an rvalue of type "pointer to cv void" (C++
1124 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001125 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001126 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001127 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001128 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 return true;
1130 }
1131
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001132 // When we're overloading in C, we allow a special kind of pointer
1133 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001134 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001135 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001136 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001137 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001138 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001139 return true;
1140 }
1141
Douglas Gregor5c407d92008-10-23 00:40:37 +00001142 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001143 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001144 // An rvalue of type "pointer to cv D," where D is a class type,
1145 // can be converted to an rvalue of type "pointer to cv B," where
1146 // B is a base class (clause 10) of D. If B is an inaccessible
1147 // (clause 11) or ambiguous (10.2) base class of D, a program that
1148 // necessitates this conversion is ill-formed. The result of the
1149 // conversion is a pointer to the base class sub-object of the
1150 // derived class object. The null pointer value is converted to
1151 // the null pointer value of the destination type.
1152 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001153 // Note that we do not check for ambiguity or inaccessibility
1154 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001155 if (getLangOptions().CPlusPlus &&
1156 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001157 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001158 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001159 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001160 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001161 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001162 ToType, Context);
1163 return true;
1164 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001165
Douglas Gregora119f102008-12-19 19:13:09 +00001166 return false;
1167}
1168
1169/// isObjCPointerConversion - Determines whether this is an
1170/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1171/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001172bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001173 QualType& ConvertedType,
1174 bool &IncompatibleObjC) {
1175 if (!getLangOptions().ObjC1)
1176 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001177
Steve Naroff7cae42b2009-07-10 23:34:53 +00001178 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001179 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001180 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001181 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001182
Steve Naroff7cae42b2009-07-10 23:34:53 +00001183 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001184 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001185 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001186 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001187 ConvertedType = ToType;
1188 return true;
1189 }
1190 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001191 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001192 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001193 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001194 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001195 ConvertedType = ToType;
1196 return true;
1197 }
1198 // Objective C++: We're able to convert from a pointer to an
1199 // interface to a pointer to a different interface.
1200 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001201 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1202 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1203 if (getLangOptions().CPlusPlus && LHS && RHS &&
1204 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1205 FromObjCPtr->getPointeeType()))
1206 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001207 ConvertedType = ToType;
1208 return true;
1209 }
1210
1211 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1212 // Okay: this is some kind of implicit downcast of Objective-C
1213 // interfaces, which is permitted. However, we're going to
1214 // complain about it.
1215 IncompatibleObjC = true;
1216 ConvertedType = FromType;
1217 return true;
1218 }
Mike Stump11289f42009-09-09 15:08:12 +00001219 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001220 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001221 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001222 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001223 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001224 else if (const BlockPointerType *ToBlockPtr =
1225 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001226 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001227 // to a block pointer type.
1228 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1229 ConvertedType = ToType;
1230 return true;
1231 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001232 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001233 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001234 else if (FromType->getAs<BlockPointerType>() &&
1235 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1236 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001237 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001238 ConvertedType = ToType;
1239 return true;
1240 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001241 else
Douglas Gregora119f102008-12-19 19:13:09 +00001242 return false;
1243
Douglas Gregor033f56d2008-12-23 00:53:59 +00001244 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001245 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001246 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001247 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001248 FromPointeeType = FromBlockPtr->getPointeeType();
1249 else
Douglas Gregora119f102008-12-19 19:13:09 +00001250 return false;
1251
Douglas Gregora119f102008-12-19 19:13:09 +00001252 // If we have pointers to pointers, recursively check whether this
1253 // is an Objective-C conversion.
1254 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1255 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1256 IncompatibleObjC)) {
1257 // We always complain about this conversion.
1258 IncompatibleObjC = true;
1259 ConvertedType = ToType;
1260 return true;
1261 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001262 // Allow conversion of pointee being objective-c pointer to another one;
1263 // as in I* to id.
1264 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1265 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1266 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1267 IncompatibleObjC)) {
1268 ConvertedType = ToType;
1269 return true;
1270 }
1271
Douglas Gregor033f56d2008-12-23 00:53:59 +00001272 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001273 // differences in the argument and result types are in Objective-C
1274 // pointer conversions. If so, we permit the conversion (but
1275 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001276 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001277 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001278 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001279 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001280 if (FromFunctionType && ToFunctionType) {
1281 // If the function types are exactly the same, this isn't an
1282 // Objective-C pointer conversion.
1283 if (Context.getCanonicalType(FromPointeeType)
1284 == Context.getCanonicalType(ToPointeeType))
1285 return false;
1286
1287 // Perform the quick checks that will tell us whether these
1288 // function types are obviously different.
1289 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1290 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1291 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1292 return false;
1293
1294 bool HasObjCConversion = false;
1295 if (Context.getCanonicalType(FromFunctionType->getResultType())
1296 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1297 // Okay, the types match exactly. Nothing to do.
1298 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1299 ToFunctionType->getResultType(),
1300 ConvertedType, IncompatibleObjC)) {
1301 // Okay, we have an Objective-C pointer conversion.
1302 HasObjCConversion = true;
1303 } else {
1304 // Function types are too different. Abort.
1305 return false;
1306 }
Mike Stump11289f42009-09-09 15:08:12 +00001307
Douglas Gregora119f102008-12-19 19:13:09 +00001308 // Check argument types.
1309 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1310 ArgIdx != NumArgs; ++ArgIdx) {
1311 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1312 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1313 if (Context.getCanonicalType(FromArgType)
1314 == Context.getCanonicalType(ToArgType)) {
1315 // Okay, the types match exactly. Nothing to do.
1316 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1317 ConvertedType, IncompatibleObjC)) {
1318 // Okay, we have an Objective-C pointer conversion.
1319 HasObjCConversion = true;
1320 } else {
1321 // Argument types are too different. Abort.
1322 return false;
1323 }
1324 }
1325
1326 if (HasObjCConversion) {
1327 // We had an Objective-C conversion. Allow this pointer
1328 // conversion, but complain about it.
1329 ConvertedType = ToType;
1330 IncompatibleObjC = true;
1331 return true;
1332 }
1333 }
1334
Sebastian Redl72b597d2009-01-25 19:43:20 +00001335 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001336}
1337
Douglas Gregor39c16d42008-10-24 04:54:22 +00001338/// CheckPointerConversion - Check the pointer conversion from the
1339/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001340/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001341/// conversions for which IsPointerConversion has already returned
1342/// true. It returns true and produces a diagnostic if there was an
1343/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001344bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001345 CastExpr::CastKind &Kind,
1346 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001347 QualType FromType = From->getType();
1348
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001349 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1350 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001351 QualType FromPointeeType = FromPtrType->getPointeeType(),
1352 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001353
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001354 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1355 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001356 // We must have a derived-to-base conversion. Check an
1357 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001358 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1359 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001360 From->getSourceRange(),
1361 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001362 return true;
1363
1364 // The conversion was successful.
1365 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001366 }
1367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001369 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001370 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001371 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001372 // Objective-C++ conversions are always okay.
1373 // FIXME: We should have a different class of conversions for the
1374 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001375 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001376 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001377
Steve Naroff7cae42b2009-07-10 23:34:53 +00001378 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001379 return false;
1380}
1381
Sebastian Redl72b597d2009-01-25 19:43:20 +00001382/// IsMemberPointerConversion - Determines whether the conversion of the
1383/// expression From, which has the (possibly adjusted) type FromType, can be
1384/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1385/// If so, returns true and places the converted type (that might differ from
1386/// ToType in its cv-qualifiers at some level) into ConvertedType.
1387bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001388 QualType ToType,
1389 bool InOverloadResolution,
1390 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001391 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001392 if (!ToTypePtr)
1393 return false;
1394
1395 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001396 if (From->isNullPointerConstant(Context,
1397 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1398 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001399 ConvertedType = ToType;
1400 return true;
1401 }
1402
1403 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001404 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001405 if (!FromTypePtr)
1406 return false;
1407
1408 // A pointer to member of B can be converted to a pointer to member of D,
1409 // where D is derived from B (C++ 4.11p2).
1410 QualType FromClass(FromTypePtr->getClass(), 0);
1411 QualType ToClass(ToTypePtr->getClass(), 0);
1412 // FIXME: What happens when these are dependent? Is this function even called?
1413
1414 if (IsDerivedFrom(ToClass, FromClass)) {
1415 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1416 ToClass.getTypePtr());
1417 return true;
1418 }
1419
1420 return false;
1421}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001422
Sebastian Redl72b597d2009-01-25 19:43:20 +00001423/// CheckMemberPointerConversion - Check the member pointer conversion from the
1424/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001425/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001426/// for which IsMemberPointerConversion has already returned true. It returns
1427/// true and produces a diagnostic if there was an error, or returns false
1428/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001429bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001430 CastExpr::CastKind &Kind,
1431 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001432 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001433 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001434 if (!FromPtrType) {
1435 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001436 assert(From->isNullPointerConstant(Context,
1437 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001438 "Expr must be null pointer constant!");
1439 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001440 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001441 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001442
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001443 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001444 assert(ToPtrType && "No member pointer cast has a target type "
1445 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001446
Sebastian Redled8f2002009-01-28 18:33:18 +00001447 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1448 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001449
Sebastian Redled8f2002009-01-28 18:33:18 +00001450 // FIXME: What about dependent types?
1451 assert(FromClass->isRecordType() && "Pointer into non-class.");
1452 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001453
John McCall5b0829a2010-02-10 09:31:12 +00001454 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001455 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001456 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1457 assert(DerivationOkay &&
1458 "Should not have been called if derivation isn't OK.");
1459 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001460
Sebastian Redled8f2002009-01-28 18:33:18 +00001461 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1462 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001463 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1464 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1465 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1466 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001467 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001468
Douglas Gregor89ee6822009-02-28 01:32:25 +00001469 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001470 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1471 << FromClass << ToClass << QualType(VBase, 0)
1472 << From->getSourceRange();
1473 return true;
1474 }
1475
John McCall5b0829a2010-02-10 09:31:12 +00001476 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001477 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1478 Paths.front(),
1479 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001480
Anders Carlssond7923c62009-08-22 23:33:40 +00001481 // Must be a base to derived member conversion.
1482 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001483 return false;
1484}
1485
Douglas Gregor9a657932008-10-21 23:43:52 +00001486/// IsQualificationConversion - Determines whether the conversion from
1487/// an rvalue of type FromType to ToType is a qualification conversion
1488/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001489bool
1490Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001491 FromType = Context.getCanonicalType(FromType);
1492 ToType = Context.getCanonicalType(ToType);
1493
1494 // If FromType and ToType are the same type, this is not a
1495 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001496 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001497 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001498
Douglas Gregor9a657932008-10-21 23:43:52 +00001499 // (C++ 4.4p4):
1500 // A conversion can add cv-qualifiers at levels other than the first
1501 // in multi-level pointers, subject to the following rules: [...]
1502 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001503 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001504 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001505 // Within each iteration of the loop, we check the qualifiers to
1506 // determine if this still looks like a qualification
1507 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001508 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001509 // until there are no more pointers or pointers-to-members left to
1510 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001511 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001512
1513 // -- for every j > 0, if const is in cv 1,j then const is in cv
1514 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001515 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001516 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001517
Douglas Gregor9a657932008-10-21 23:43:52 +00001518 // -- if the cv 1,j and cv 2,j are different, then const is in
1519 // every cv for 0 < k < j.
1520 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001521 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001522 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001523
Douglas Gregor9a657932008-10-21 23:43:52 +00001524 // Keep track of whether all prior cv-qualifiers in the "to" type
1525 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001526 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001527 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001528 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001529
1530 // We are left with FromType and ToType being the pointee types
1531 // after unwrapping the original FromType and ToType the same number
1532 // of types. If we unwrapped any pointers, and if FromType and
1533 // ToType have the same unqualified type (since we checked
1534 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001535 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001536}
1537
Douglas Gregor576e98c2009-01-30 23:27:23 +00001538/// Determines whether there is a user-defined conversion sequence
1539/// (C++ [over.ics.user]) that converts expression From to the type
1540/// ToType. If such a conversion exists, User will contain the
1541/// user-defined conversion sequence that performs such a conversion
1542/// and this routine will return true. Otherwise, this routine returns
1543/// false and User is unspecified.
1544///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001545/// \param AllowExplicit true if the conversion should consider C++0x
1546/// "explicit" conversion functions as well as non-explicit conversion
1547/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001548OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1549 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001550 OverloadCandidateSet& CandidateSet,
1551 bool AllowExplicit) {
1552 // Whether we will only visit constructors.
1553 bool ConstructorsOnly = false;
1554
1555 // If the type we are conversion to is a class type, enumerate its
1556 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001557 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001558 // C++ [over.match.ctor]p1:
1559 // When objects of class type are direct-initialized (8.5), or
1560 // copy-initialized from an expression of the same or a
1561 // derived class type (8.5), overload resolution selects the
1562 // constructor. [...] For copy-initialization, the candidate
1563 // functions are all the converting constructors (12.3.1) of
1564 // that class. The argument list is the expression-list within
1565 // the parentheses of the initializer.
1566 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1567 (From->getType()->getAs<RecordType>() &&
1568 IsDerivedFrom(From->getType(), ToType)))
1569 ConstructorsOnly = true;
1570
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001571 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1572 // We're not going to find any constructors.
1573 } else if (CXXRecordDecl *ToRecordDecl
1574 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001575 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001576 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001577 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001578 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001579 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001580 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001581 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001582 NamedDecl *D = *Con;
1583 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1584
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001585 // Find the constructor (which may be a template).
1586 CXXConstructorDecl *Constructor = 0;
1587 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001588 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001589 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001590 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001591 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1592 else
John McCalla0296f72010-03-19 07:35:19 +00001593 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001594
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001595 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001596 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001597 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001598 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001599 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001600 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001601 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001602 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001603 // Allow one user-defined conversion when user specifies a
1604 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001605 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001606 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001607 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001608 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001609 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001610 }
1611 }
1612
Douglas Gregor5ab11652010-04-17 22:01:05 +00001613 // Enumerate conversion functions, if we're allowed to.
1614 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001615 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001616 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001617 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001618 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001619 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001620 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001621 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1622 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001623 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001624 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001625 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001626 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001627 DeclAccessPair FoundDecl = I.getPair();
1628 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001629 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1630 if (isa<UsingShadowDecl>(D))
1631 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1632
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001633 CXXConversionDecl *Conv;
1634 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001635 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1636 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001637 else
John McCallda4458e2010-03-31 01:36:47 +00001638 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001639
1640 if (AllowExplicit || !Conv->isExplicit()) {
1641 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001642 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001643 ActingContext, From, ToType,
1644 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001645 else
John McCalla0296f72010-03-19 07:35:19 +00001646 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001647 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001648 }
1649 }
1650 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001651 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001652
1653 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001654 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001655 case OR_Success:
1656 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001657 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001658 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1659 // C++ [over.ics.user]p1:
1660 // If the user-defined conversion is specified by a
1661 // constructor (12.3.1), the initial standard conversion
1662 // sequence converts the source type to the type required by
1663 // the argument of the constructor.
1664 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001665 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001666 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001667 User.EllipsisConversion = true;
1668 else {
1669 User.Before = Best->Conversions[0].Standard;
1670 User.EllipsisConversion = false;
1671 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 User.ConversionFunction = Constructor;
1673 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001674 User.After.setFromType(
1675 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001676 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001677 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001678 } else if (CXXConversionDecl *Conversion
1679 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1680 // C++ [over.ics.user]p1:
1681 //
1682 // [...] If the user-defined conversion is specified by a
1683 // conversion function (12.3.2), the initial standard
1684 // conversion sequence converts the source type to the
1685 // implicit object parameter of the conversion function.
1686 User.Before = Best->Conversions[0].Standard;
1687 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001688 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001689
1690 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001691 // The second standard conversion sequence converts the
1692 // result of the user-defined conversion to the target type
1693 // for the sequence. Since an implicit conversion sequence
1694 // is an initialization, the special rules for
1695 // initialization by user-defined conversion apply when
1696 // selecting the best user-defined conversion for a
1697 // user-defined conversion sequence (see 13.3.3 and
1698 // 13.3.3.1).
1699 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001700 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001701 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001702 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001703 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001706 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001707 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001708 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001709 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001710 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001711
1712 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001713 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001714 }
1715
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001716 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001717}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001718
1719bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001720Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001721 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001722 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001723 OverloadingResult OvResult =
1724 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001725 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001726 if (OvResult == OR_Ambiguous)
1727 Diag(From->getSourceRange().getBegin(),
1728 diag::err_typecheck_ambiguous_condition)
1729 << From->getType() << ToType << From->getSourceRange();
1730 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1731 Diag(From->getSourceRange().getBegin(),
1732 diag::err_typecheck_nonviable_condition)
1733 << From->getType() << ToType << From->getSourceRange();
1734 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001735 return false;
John McCallad907772010-01-12 07:18:19 +00001736 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001737 return true;
1738}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001739
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001740/// CompareImplicitConversionSequences - Compare two implicit
1741/// conversion sequences to determine whether one is better than the
1742/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001743ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001744Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1745 const ImplicitConversionSequence& ICS2)
1746{
1747 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1748 // conversion sequences (as defined in 13.3.3.1)
1749 // -- a standard conversion sequence (13.3.3.1.1) is a better
1750 // conversion sequence than a user-defined conversion sequence or
1751 // an ellipsis conversion sequence, and
1752 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1753 // conversion sequence than an ellipsis conversion sequence
1754 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001755 //
John McCall0d1da222010-01-12 00:44:57 +00001756 // C++0x [over.best.ics]p10:
1757 // For the purpose of ranking implicit conversion sequences as
1758 // described in 13.3.3.2, the ambiguous conversion sequence is
1759 // treated as a user-defined sequence that is indistinguishable
1760 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00001761 if (ICS1.getKindRank() < ICS2.getKindRank())
1762 return ImplicitConversionSequence::Better;
1763 else if (ICS2.getKindRank() < ICS1.getKindRank())
1764 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001765
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00001766 // The following checks require both conversion sequences to be of
1767 // the same kind.
1768 if (ICS1.getKind() != ICS2.getKind())
1769 return ImplicitConversionSequence::Indistinguishable;
1770
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001771 // Two implicit conversion sequences of the same form are
1772 // indistinguishable conversion sequences unless one of the
1773 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001774 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001775 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001776 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001777 // User-defined conversion sequence U1 is a better conversion
1778 // sequence than another user-defined conversion sequence U2 if
1779 // they contain the same user-defined conversion function or
1780 // constructor and if the second standard conversion sequence of
1781 // U1 is better than the second standard conversion sequence of
1782 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001783 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001784 ICS2.UserDefined.ConversionFunction)
1785 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1786 ICS2.UserDefined.After);
1787 }
1788
1789 return ImplicitConversionSequence::Indistinguishable;
1790}
1791
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001792// Per 13.3.3.2p3, compare the given standard conversion sequences to
1793// determine if one is a proper subset of the other.
1794static ImplicitConversionSequence::CompareKind
1795compareStandardConversionSubsets(ASTContext &Context,
1796 const StandardConversionSequence& SCS1,
1797 const StandardConversionSequence& SCS2) {
1798 ImplicitConversionSequence::CompareKind Result
1799 = ImplicitConversionSequence::Indistinguishable;
1800
1801 if (SCS1.Second != SCS2.Second) {
1802 if (SCS1.Second == ICK_Identity)
1803 Result = ImplicitConversionSequence::Better;
1804 else if (SCS2.Second == ICK_Identity)
1805 Result = ImplicitConversionSequence::Worse;
1806 else
1807 return ImplicitConversionSequence::Indistinguishable;
1808 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1809 return ImplicitConversionSequence::Indistinguishable;
1810
1811 if (SCS1.Third == SCS2.Third) {
1812 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1813 : ImplicitConversionSequence::Indistinguishable;
1814 }
1815
1816 if (SCS1.Third == ICK_Identity)
1817 return Result == ImplicitConversionSequence::Worse
1818 ? ImplicitConversionSequence::Indistinguishable
1819 : ImplicitConversionSequence::Better;
1820
1821 if (SCS2.Third == ICK_Identity)
1822 return Result == ImplicitConversionSequence::Better
1823 ? ImplicitConversionSequence::Indistinguishable
1824 : ImplicitConversionSequence::Worse;
1825
1826 return ImplicitConversionSequence::Indistinguishable;
1827}
1828
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001829/// CompareStandardConversionSequences - Compare two standard
1830/// conversion sequences to determine whether one is better than the
1831/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001832ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001833Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1834 const StandardConversionSequence& SCS2)
1835{
1836 // Standard conversion sequence S1 is a better conversion sequence
1837 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1838
1839 // -- S1 is a proper subsequence of S2 (comparing the conversion
1840 // sequences in the canonical form defined by 13.3.3.1.1,
1841 // excluding any Lvalue Transformation; the identity conversion
1842 // sequence is considered to be a subsequence of any
1843 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001844 if (ImplicitConversionSequence::CompareKind CK
1845 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1846 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001847
1848 // -- the rank of S1 is better than the rank of S2 (by the rules
1849 // defined below), or, if not that,
1850 ImplicitConversionRank Rank1 = SCS1.getRank();
1851 ImplicitConversionRank Rank2 = SCS2.getRank();
1852 if (Rank1 < Rank2)
1853 return ImplicitConversionSequence::Better;
1854 else if (Rank2 < Rank1)
1855 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001856
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001857 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1858 // are indistinguishable unless one of the following rules
1859 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001860
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001861 // A conversion that is not a conversion of a pointer, or
1862 // pointer to member, to bool is better than another conversion
1863 // that is such a conversion.
1864 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1865 return SCS2.isPointerConversionToBool()
1866 ? ImplicitConversionSequence::Better
1867 : ImplicitConversionSequence::Worse;
1868
Douglas Gregor5c407d92008-10-23 00:40:37 +00001869 // C++ [over.ics.rank]p4b2:
1870 //
1871 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001872 // conversion of B* to A* is better than conversion of B* to
1873 // void*, and conversion of A* to void* is better than conversion
1874 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001875 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001876 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001877 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001878 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001879 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1880 // Exactly one of the conversion sequences is a conversion to
1881 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001882 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1883 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001884 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1885 // Neither conversion sequence converts to a void pointer; compare
1886 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001887 if (ImplicitConversionSequence::CompareKind DerivedCK
1888 = CompareDerivedToBaseConversions(SCS1, SCS2))
1889 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001890 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1891 // Both conversion sequences are conversions to void
1892 // pointers. Compare the source types to determine if there's an
1893 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001894 QualType FromType1 = SCS1.getFromType();
1895 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001896
1897 // Adjust the types we're converting from via the array-to-pointer
1898 // conversion, if we need to.
1899 if (SCS1.First == ICK_Array_To_Pointer)
1900 FromType1 = Context.getArrayDecayedType(FromType1);
1901 if (SCS2.First == ICK_Array_To_Pointer)
1902 FromType2 = Context.getArrayDecayedType(FromType2);
1903
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001904 QualType FromPointee1
1905 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1906 QualType FromPointee2
1907 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001908
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001909 if (IsDerivedFrom(FromPointee2, FromPointee1))
1910 return ImplicitConversionSequence::Better;
1911 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1912 return ImplicitConversionSequence::Worse;
1913
1914 // Objective-C++: If one interface is more specific than the
1915 // other, it is the better one.
1916 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1917 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1918 if (FromIface1 && FromIface1) {
1919 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1920 return ImplicitConversionSequence::Better;
1921 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1922 return ImplicitConversionSequence::Worse;
1923 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001924 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001925
1926 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1927 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001928 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001929 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001930 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001931
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001932 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001933 // C++0x [over.ics.rank]p3b4:
1934 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1935 // implicit object parameter of a non-static member function declared
1936 // without a ref-qualifier, and S1 binds an rvalue reference to an
1937 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001938 // FIXME: We don't know if we're dealing with the implicit object parameter,
1939 // or if the member function in this case has a ref qualifier.
1940 // (Of course, we don't have ref qualifiers yet.)
1941 if (SCS1.RRefBinding != SCS2.RRefBinding)
1942 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1943 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001944
1945 // C++ [over.ics.rank]p3b4:
1946 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1947 // which the references refer are the same type except for
1948 // top-level cv-qualifiers, and the type to which the reference
1949 // initialized by S2 refers is more cv-qualified than the type
1950 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001951 QualType T1 = SCS1.getToType(2);
1952 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001953 T1 = Context.getCanonicalType(T1);
1954 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001955 Qualifiers T1Quals, T2Quals;
1956 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1957 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1958 if (UnqualT1 == UnqualT2) {
1959 // If the type is an array type, promote the element qualifiers to the type
1960 // for comparison.
1961 if (isa<ArrayType>(T1) && T1Quals)
1962 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1963 if (isa<ArrayType>(T2) && T2Quals)
1964 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001965 if (T2.isMoreQualifiedThan(T1))
1966 return ImplicitConversionSequence::Better;
1967 else if (T1.isMoreQualifiedThan(T2))
1968 return ImplicitConversionSequence::Worse;
1969 }
1970 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001971
1972 return ImplicitConversionSequence::Indistinguishable;
1973}
1974
1975/// CompareQualificationConversions - Compares two standard conversion
1976/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001977/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1978ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001979Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001980 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001981 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001982 // -- S1 and S2 differ only in their qualification conversion and
1983 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1984 // cv-qualification signature of type T1 is a proper subset of
1985 // the cv-qualification signature of type T2, and S1 is not the
1986 // deprecated string literal array-to-pointer conversion (4.2).
1987 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1988 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1989 return ImplicitConversionSequence::Indistinguishable;
1990
1991 // FIXME: the example in the standard doesn't use a qualification
1992 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001993 QualType T1 = SCS1.getToType(2);
1994 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001995 T1 = Context.getCanonicalType(T1);
1996 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001997 Qualifiers T1Quals, T2Quals;
1998 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1999 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002000
2001 // If the types are the same, we won't learn anything by unwrapped
2002 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002003 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002004 return ImplicitConversionSequence::Indistinguishable;
2005
Chandler Carruth607f38e2009-12-29 07:16:59 +00002006 // If the type is an array type, promote the element qualifiers to the type
2007 // for comparison.
2008 if (isa<ArrayType>(T1) && T1Quals)
2009 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2010 if (isa<ArrayType>(T2) && T2Quals)
2011 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2012
Mike Stump11289f42009-09-09 15:08:12 +00002013 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002014 = ImplicitConversionSequence::Indistinguishable;
2015 while (UnwrapSimilarPointerTypes(T1, T2)) {
2016 // Within each iteration of the loop, we check the qualifiers to
2017 // determine if this still looks like a qualification
2018 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002019 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002020 // until there are no more pointers or pointers-to-members left
2021 // to unwrap. This essentially mimics what
2022 // IsQualificationConversion does, but here we're checking for a
2023 // strict subset of qualifiers.
2024 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2025 // The qualifiers are the same, so this doesn't tell us anything
2026 // about how the sequences rank.
2027 ;
2028 else if (T2.isMoreQualifiedThan(T1)) {
2029 // T1 has fewer qualifiers, so it could be the better sequence.
2030 if (Result == ImplicitConversionSequence::Worse)
2031 // Neither has qualifiers that are a subset of the other's
2032 // qualifiers.
2033 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002034
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002035 Result = ImplicitConversionSequence::Better;
2036 } else if (T1.isMoreQualifiedThan(T2)) {
2037 // T2 has fewer qualifiers, so it could be the better sequence.
2038 if (Result == ImplicitConversionSequence::Better)
2039 // Neither has qualifiers that are a subset of the other's
2040 // qualifiers.
2041 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002042
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002043 Result = ImplicitConversionSequence::Worse;
2044 } else {
2045 // Qualifiers are disjoint.
2046 return ImplicitConversionSequence::Indistinguishable;
2047 }
2048
2049 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002050 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002051 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002052 }
2053
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002054 // Check that the winning standard conversion sequence isn't using
2055 // the deprecated string literal array to pointer conversion.
2056 switch (Result) {
2057 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002058 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002059 Result = ImplicitConversionSequence::Indistinguishable;
2060 break;
2061
2062 case ImplicitConversionSequence::Indistinguishable:
2063 break;
2064
2065 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002066 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002067 Result = ImplicitConversionSequence::Indistinguishable;
2068 break;
2069 }
2070
2071 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002072}
2073
Douglas Gregor5c407d92008-10-23 00:40:37 +00002074/// CompareDerivedToBaseConversions - Compares two standard conversion
2075/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002076/// various kinds of derived-to-base conversions (C++
2077/// [over.ics.rank]p4b3). As part of these checks, we also look at
2078/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002079ImplicitConversionSequence::CompareKind
2080Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2081 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002082 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002083 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002084 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002085 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002086
2087 // Adjust the types we're converting from via the array-to-pointer
2088 // conversion, if we need to.
2089 if (SCS1.First == ICK_Array_To_Pointer)
2090 FromType1 = Context.getArrayDecayedType(FromType1);
2091 if (SCS2.First == ICK_Array_To_Pointer)
2092 FromType2 = Context.getArrayDecayedType(FromType2);
2093
2094 // Canonicalize all of the types.
2095 FromType1 = Context.getCanonicalType(FromType1);
2096 ToType1 = Context.getCanonicalType(ToType1);
2097 FromType2 = Context.getCanonicalType(FromType2);
2098 ToType2 = Context.getCanonicalType(ToType2);
2099
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002100 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002101 //
2102 // If class B is derived directly or indirectly from class A and
2103 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002104 //
2105 // For Objective-C, we let A, B, and C also be Objective-C
2106 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002107
2108 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002109 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002110 SCS2.Second == ICK_Pointer_Conversion &&
2111 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2112 FromType1->isPointerType() && FromType2->isPointerType() &&
2113 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002114 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002115 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002116 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002117 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002118 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002119 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002120 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002121 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002122
John McCall9dd450b2009-09-21 23:43:11 +00002123 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2124 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2125 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2126 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002127
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002128 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002129 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2130 if (IsDerivedFrom(ToPointee1, ToPointee2))
2131 return ImplicitConversionSequence::Better;
2132 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2133 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002134
2135 if (ToIface1 && ToIface2) {
2136 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2137 return ImplicitConversionSequence::Better;
2138 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2139 return ImplicitConversionSequence::Worse;
2140 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002141 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002142
2143 // -- conversion of B* to A* is better than conversion of C* to A*,
2144 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2145 if (IsDerivedFrom(FromPointee2, FromPointee1))
2146 return ImplicitConversionSequence::Better;
2147 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2148 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002149
Douglas Gregor237f96c2008-11-26 23:31:11 +00002150 if (FromIface1 && FromIface2) {
2151 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2152 return ImplicitConversionSequence::Better;
2153 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2154 return ImplicitConversionSequence::Worse;
2155 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002156 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002157 }
2158
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002159 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002160 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2161 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2162 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2163 const MemberPointerType * FromMemPointer1 =
2164 FromType1->getAs<MemberPointerType>();
2165 const MemberPointerType * ToMemPointer1 =
2166 ToType1->getAs<MemberPointerType>();
2167 const MemberPointerType * FromMemPointer2 =
2168 FromType2->getAs<MemberPointerType>();
2169 const MemberPointerType * ToMemPointer2 =
2170 ToType2->getAs<MemberPointerType>();
2171 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2172 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2173 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2174 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2175 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2176 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2177 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2178 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002179 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002180 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2181 if (IsDerivedFrom(ToPointee1, ToPointee2))
2182 return ImplicitConversionSequence::Worse;
2183 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2184 return ImplicitConversionSequence::Better;
2185 }
2186 // conversion of B::* to C::* is better than conversion of A::* to C::*
2187 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2188 if (IsDerivedFrom(FromPointee1, FromPointee2))
2189 return ImplicitConversionSequence::Better;
2190 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2191 return ImplicitConversionSequence::Worse;
2192 }
2193 }
2194
Douglas Gregor5ab11652010-04-17 22:01:05 +00002195 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002196 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002197 // -- binding of an expression of type C to a reference of type
2198 // B& is better than binding an expression of type C to a
2199 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002200 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2201 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002202 if (IsDerivedFrom(ToType1, ToType2))
2203 return ImplicitConversionSequence::Better;
2204 else if (IsDerivedFrom(ToType2, ToType1))
2205 return ImplicitConversionSequence::Worse;
2206 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002207
Douglas Gregor2fe98832008-11-03 19:09:14 +00002208 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002209 // -- binding of an expression of type B to a reference of type
2210 // A& is better than binding an expression of type C to a
2211 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002212 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2213 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002214 if (IsDerivedFrom(FromType2, FromType1))
2215 return ImplicitConversionSequence::Better;
2216 else if (IsDerivedFrom(FromType1, FromType2))
2217 return ImplicitConversionSequence::Worse;
2218 }
2219 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002220
Douglas Gregor5c407d92008-10-23 00:40:37 +00002221 return ImplicitConversionSequence::Indistinguishable;
2222}
2223
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002224/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2225/// determine whether they are reference-related,
2226/// reference-compatible, reference-compatible with added
2227/// qualification, or incompatible, for use in C++ initialization by
2228/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2229/// type, and the first type (T1) is the pointee type of the reference
2230/// type being initialized.
2231Sema::ReferenceCompareResult
2232Sema::CompareReferenceRelationship(SourceLocation Loc,
2233 QualType OrigT1, QualType OrigT2,
2234 bool& DerivedToBase) {
2235 assert(!OrigT1->isReferenceType() &&
2236 "T1 must be the pointee type of the reference type");
2237 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2238
2239 QualType T1 = Context.getCanonicalType(OrigT1);
2240 QualType T2 = Context.getCanonicalType(OrigT2);
2241 Qualifiers T1Quals, T2Quals;
2242 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2243 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2244
2245 // C++ [dcl.init.ref]p4:
2246 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2247 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2248 // T1 is a base class of T2.
2249 if (UnqualT1 == UnqualT2)
2250 DerivedToBase = false;
2251 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
2252 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
2253 IsDerivedFrom(UnqualT2, UnqualT1))
2254 DerivedToBase = true;
2255 else
2256 return Ref_Incompatible;
2257
2258 // At this point, we know that T1 and T2 are reference-related (at
2259 // least).
2260
2261 // If the type is an array type, promote the element qualifiers to the type
2262 // for comparison.
2263 if (isa<ArrayType>(T1) && T1Quals)
2264 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2265 if (isa<ArrayType>(T2) && T2Quals)
2266 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2267
2268 // C++ [dcl.init.ref]p4:
2269 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2270 // reference-related to T2 and cv1 is the same cv-qualification
2271 // as, or greater cv-qualification than, cv2. For purposes of
2272 // overload resolution, cases for which cv1 is greater
2273 // cv-qualification than cv2 are identified as
2274 // reference-compatible with added qualification (see 13.3.3.2).
2275 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2276 return Ref_Compatible;
2277 else if (T1.isMoreQualifiedThan(T2))
2278 return Ref_Compatible_With_Added_Qualification;
2279 else
2280 return Ref_Related;
2281}
2282
2283/// \brief Compute an implicit conversion sequence for reference
2284/// initialization.
2285static ImplicitConversionSequence
2286TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2287 SourceLocation DeclLoc,
2288 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002289 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002290 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2291
2292 // Most paths end in a failed conversion.
2293 ImplicitConversionSequence ICS;
2294 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2295
2296 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2297 QualType T2 = Init->getType();
2298
2299 // If the initializer is the address of an overloaded function, try
2300 // to resolve the overloaded function. If all goes well, T2 is the
2301 // type of the resulting function.
2302 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2303 DeclAccessPair Found;
2304 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2305 false, Found))
2306 T2 = Fn->getType();
2307 }
2308
2309 // Compute some basic properties of the types and the initializer.
2310 bool isRValRef = DeclType->isRValueReferenceType();
2311 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002312 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002313 Sema::ReferenceCompareResult RefRelationship
2314 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2315
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002316
2317 // C++ [over.ics.ref]p3:
2318 // Except for an implicit object parameter, for which see 13.3.1,
2319 // a standard conversion sequence cannot be formed if it requires
2320 // binding an lvalue reference to non-const to an rvalue or
2321 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002322 //
2323 // FIXME: DPG doesn't trust this code. It seems far too early to
2324 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002325 if (isRValRef && InitLvalue == Expr::LV_Valid)
2326 return ICS;
2327
Douglas Gregor870f3742010-04-18 09:22:00 +00002328 // C++0x [dcl.init.ref]p16:
2329 // A reference to type "cv1 T1" is initialized by an expression
2330 // of type "cv2 T2" as follows:
2331
2332 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002333 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2334 // reference-compatible with "cv2 T2," or
2335 //
2336 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2337 if (InitLvalue == Expr::LV_Valid &&
2338 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2339 // C++ [over.ics.ref]p1:
2340 // When a parameter of reference type binds directly (8.5.3)
2341 // to an argument expression, the implicit conversion sequence
2342 // is the identity conversion, unless the argument expression
2343 // has a type that is a derived class of the parameter type,
2344 // in which case the implicit conversion sequence is a
2345 // derived-to-base Conversion (13.3.3.1).
2346 ICS.setStandard();
2347 ICS.Standard.First = ICK_Identity;
2348 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2349 ICS.Standard.Third = ICK_Identity;
2350 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2351 ICS.Standard.setToType(0, T2);
2352 ICS.Standard.setToType(1, T1);
2353 ICS.Standard.setToType(2, T1);
2354 ICS.Standard.ReferenceBinding = true;
2355 ICS.Standard.DirectBinding = true;
2356 ICS.Standard.RRefBinding = false;
2357 ICS.Standard.CopyConstructor = 0;
2358
2359 // Nothing more to do: the inaccessibility/ambiguity check for
2360 // derived-to-base conversions is suppressed when we're
2361 // computing the implicit conversion sequence (C++
2362 // [over.best.ics]p2).
2363 return ICS;
2364 }
2365
2366 // -- has a class type (i.e., T2 is a class type), where T1 is
2367 // not reference-related to T2, and can be implicitly
2368 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2369 // is reference-compatible with "cv3 T3" 92) (this
2370 // conversion is selected by enumerating the applicable
2371 // conversion functions (13.3.1.6) and choosing the best
2372 // one through overload resolution (13.3)),
2373 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2374 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2375 RefRelationship == Sema::Ref_Incompatible) {
2376 CXXRecordDecl *T2RecordDecl
2377 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2378
2379 OverloadCandidateSet CandidateSet(DeclLoc);
2380 const UnresolvedSetImpl *Conversions
2381 = T2RecordDecl->getVisibleConversionFunctions();
2382 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2383 E = Conversions->end(); I != E; ++I) {
2384 NamedDecl *D = *I;
2385 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2386 if (isa<UsingShadowDecl>(D))
2387 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2388
2389 FunctionTemplateDecl *ConvTemplate
2390 = dyn_cast<FunctionTemplateDecl>(D);
2391 CXXConversionDecl *Conv;
2392 if (ConvTemplate)
2393 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2394 else
2395 Conv = cast<CXXConversionDecl>(D);
2396
2397 // If the conversion function doesn't return a reference type,
2398 // it can't be considered for this conversion.
2399 if (Conv->getConversionType()->isLValueReferenceType() &&
2400 (AllowExplicit || !Conv->isExplicit())) {
2401 if (ConvTemplate)
2402 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2403 Init, DeclType, CandidateSet);
2404 else
2405 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2406 DeclType, CandidateSet);
2407 }
2408 }
2409
2410 OverloadCandidateSet::iterator Best;
2411 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2412 case OR_Success:
2413 // C++ [over.ics.ref]p1:
2414 //
2415 // [...] If the parameter binds directly to the result of
2416 // applying a conversion function to the argument
2417 // expression, the implicit conversion sequence is a
2418 // user-defined conversion sequence (13.3.3.1.2), with the
2419 // second standard conversion sequence either an identity
2420 // conversion or, if the conversion function returns an
2421 // entity of a type that is a derived class of the parameter
2422 // type, a derived-to-base Conversion.
2423 if (!Best->FinalConversion.DirectBinding)
2424 break;
2425
2426 ICS.setUserDefined();
2427 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2428 ICS.UserDefined.After = Best->FinalConversion;
2429 ICS.UserDefined.ConversionFunction = Best->Function;
2430 ICS.UserDefined.EllipsisConversion = false;
2431 assert(ICS.UserDefined.After.ReferenceBinding &&
2432 ICS.UserDefined.After.DirectBinding &&
2433 "Expected a direct reference binding!");
2434 return ICS;
2435
2436 case OR_Ambiguous:
2437 ICS.setAmbiguous();
2438 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2439 Cand != CandidateSet.end(); ++Cand)
2440 if (Cand->Viable)
2441 ICS.Ambiguous.addConversion(Cand->Function);
2442 return ICS;
2443
2444 case OR_No_Viable_Function:
2445 case OR_Deleted:
2446 // There was no suitable conversion, or we found a deleted
2447 // conversion; continue with other checks.
2448 break;
2449 }
2450 }
2451
2452 // -- Otherwise, the reference shall be to a non-volatile const
2453 // type (i.e., cv1 shall be const), or the reference shall be an
2454 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002455 //
2456 // We actually handle one oddity of C++ [over.ics.ref] at this
2457 // point, which is that, due to p2 (which short-circuits reference
2458 // binding by only attempting a simple conversion for non-direct
2459 // bindings) and p3's strange wording, we allow a const volatile
2460 // reference to bind to an rvalue. Hence the check for the presence
2461 // of "const" rather than checking for "const" being the only
2462 // qualifier.
2463 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002464 return ICS;
2465
Douglas Gregorf93df192010-04-18 08:46:23 +00002466 // -- if T2 is a class type and
2467 // -- the initializer expression is an rvalue and "cv1 T1"
2468 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002469 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002470 // -- T1 is not reference-related to T2 and the initializer
2471 // expression can be implicitly converted to an rvalue
2472 // of type "cv3 T3" (this conversion is selected by
2473 // enumerating the applicable conversion functions
2474 // (13.3.1.6) and choosing the best one through overload
2475 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002476 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002477 // then the reference is bound to the initializer
2478 // expression rvalue in the first case and to the object
2479 // that is the result of the conversion in the second case
2480 // (or, in either case, to the appropriate base class
2481 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002482 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002483 // We're only checking the first case here, which is a direct
2484 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002485 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2486 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2487 ICS.setStandard();
2488 ICS.Standard.First = ICK_Identity;
2489 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2490 ICS.Standard.Third = ICK_Identity;
2491 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2492 ICS.Standard.setToType(0, T2);
2493 ICS.Standard.setToType(1, T1);
2494 ICS.Standard.setToType(2, T1);
2495 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002496 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002497 ICS.Standard.RRefBinding = isRValRef;
2498 ICS.Standard.CopyConstructor = 0;
2499 return ICS;
2500 }
2501
2502 // -- Otherwise, a temporary of type "cv1 T1" is created and
2503 // initialized from the initializer expression using the
2504 // rules for a non-reference copy initialization (8.5). The
2505 // reference is then bound to the temporary. If T1 is
2506 // reference-related to T2, cv1 must be the same
2507 // cv-qualification as, or greater cv-qualification than,
2508 // cv2; otherwise, the program is ill-formed.
2509 if (RefRelationship == Sema::Ref_Related) {
2510 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2511 // we would be reference-compatible or reference-compatible with
2512 // added qualification. But that wasn't the case, so the reference
2513 // initialization fails.
2514 return ICS;
2515 }
2516
2517 // If at least one of the types is a class type, the types are not
2518 // related, and we aren't allowed any user conversions, the
2519 // reference binding fails. This case is important for breaking
2520 // recursion, since TryImplicitConversion below will attempt to
2521 // create a temporary through the use of a copy constructor.
2522 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2523 (T1->isRecordType() || T2->isRecordType()))
2524 return ICS;
2525
2526 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002527 // When a parameter of reference type is not bound directly to
2528 // an argument expression, the conversion sequence is the one
2529 // required to convert the argument expression to the
2530 // underlying type of the reference according to
2531 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2532 // to copy-initializing a temporary of the underlying type with
2533 // the argument expression. Any difference in top-level
2534 // cv-qualification is subsumed by the initialization itself
2535 // and does not constitute a conversion.
2536 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2537 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002538 /*InOverloadResolution=*/false);
2539
2540 // Of course, that's still a reference binding.
2541 if (ICS.isStandard()) {
2542 ICS.Standard.ReferenceBinding = true;
2543 ICS.Standard.RRefBinding = isRValRef;
2544 } else if (ICS.isUserDefined()) {
2545 ICS.UserDefined.After.ReferenceBinding = true;
2546 ICS.UserDefined.After.RRefBinding = isRValRef;
2547 }
2548 return ICS;
2549}
2550
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002551/// TryCopyInitialization - Try to copy-initialize a value of type
2552/// ToType from the expression From. Return the implicit conversion
2553/// sequence required to pass this argument, which may be a bad
2554/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002555/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002556/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002557static ImplicitConversionSequence
2558TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002559 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002560 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002561 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002562 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002563 /*FIXME:*/From->getLocStart(),
2564 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002565 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002566
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002567 return S.TryImplicitConversion(From, ToType,
2568 SuppressUserConversions,
2569 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002570 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002571}
2572
Douglas Gregor436424c2008-11-18 23:14:02 +00002573/// TryObjectArgumentInitialization - Try to initialize the object
2574/// parameter of the given member function (@c Method) from the
2575/// expression @p From.
2576ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002577Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002578 CXXMethodDecl *Method,
2579 CXXRecordDecl *ActingContext) {
2580 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002581 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2582 // const volatile object.
2583 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2584 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2585 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002586
2587 // Set up the conversion sequence as a "bad" conversion, to allow us
2588 // to exit early.
2589 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002590
2591 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002592 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002593 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002594 FromType = PT->getPointeeType();
2595
2596 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002597
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002598 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002599 // where X is the class of which the function is a member
2600 // (C++ [over.match.funcs]p4). However, when finding an implicit
2601 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002602 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002603 // (C++ [over.match.funcs]p5). We perform a simplified version of
2604 // reference binding here, that allows class rvalues to bind to
2605 // non-constant references.
2606
2607 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2608 // with the implicit object parameter (C++ [over.match.funcs]p5).
2609 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002610 if (ImplicitParamType.getCVRQualifiers()
2611 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002612 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002613 ICS.setBad(BadConversionSequence::bad_qualifiers,
2614 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002615 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002616 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002617
2618 // Check that we have either the same type or a derived type. It
2619 // affects the conversion rank.
2620 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002621 ImplicitConversionKind SecondKind;
2622 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2623 SecondKind = ICK_Identity;
2624 } else if (IsDerivedFrom(FromType, ClassType))
2625 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002626 else {
John McCall65eb8792010-02-25 01:37:24 +00002627 ICS.setBad(BadConversionSequence::unrelated_class,
2628 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002629 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002630 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002631
2632 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002633 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002634 ICS.Standard.setAsIdentityConversion();
2635 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002636 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002637 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002638 ICS.Standard.ReferenceBinding = true;
2639 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002640 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002641 return ICS;
2642}
2643
2644/// PerformObjectArgumentInitialization - Perform initialization of
2645/// the implicit object parameter for the given Method with the given
2646/// expression.
2647bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002648Sema::PerformObjectArgumentInitialization(Expr *&From,
2649 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002650 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002651 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002652 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002653 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002654 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002655
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002656 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002657 FromRecordType = PT->getPointeeType();
2658 DestType = Method->getThisType(Context);
2659 } else {
2660 FromRecordType = From->getType();
2661 DestType = ImplicitParamRecordType;
2662 }
2663
John McCall6e9f8f62009-12-03 04:06:58 +00002664 // Note that we always use the true parent context when performing
2665 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002666 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002667 = TryObjectArgumentInitialization(From->getType(), Method,
2668 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002669 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002670 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002671 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002672 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002673
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002674 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002675 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002676
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002677 if (!Context.hasSameType(From->getType(), DestType))
2678 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2679 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002680 return false;
2681}
2682
Douglas Gregor5fb53972009-01-14 15:45:31 +00002683/// TryContextuallyConvertToBool - Attempt to contextually convert the
2684/// expression From to bool (C++0x [conv]p3).
2685ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002686 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002687 // FIXME: Are these flags correct?
2688 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002689 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002690 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002691}
2692
2693/// PerformContextuallyConvertToBool - Perform a contextual conversion
2694/// of the expression From to bool (C++0x [conv]p3).
2695bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2696 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002697 if (!ICS.isBad())
2698 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002699
Fariborz Jahanian76197412009-11-18 18:26:29 +00002700 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002701 return Diag(From->getSourceRange().getBegin(),
2702 diag::err_typecheck_bool_condition)
2703 << From->getType() << From->getSourceRange();
2704 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002705}
2706
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002707/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002708/// candidate functions, using the given function call arguments. If
2709/// @p SuppressUserConversions, then don't allow user-defined
2710/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002711///
2712/// \para PartialOverloading true if we are performing "partial" overloading
2713/// based on an incomplete set of function arguments. This feature is used by
2714/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002715void
2716Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002717 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002718 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002719 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002720 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002721 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002722 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002723 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002724 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002725 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002726 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002727
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002728 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002729 if (!isa<CXXConstructorDecl>(Method)) {
2730 // If we get here, it's because we're calling a member function
2731 // that is named without a member access expression (e.g.,
2732 // "this->f") that was either written explicitly or created
2733 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002734 // function, e.g., X::f(). We use an empty type for the implied
2735 // object argument (C++ [over.call.func]p3), and the acting context
2736 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002737 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002738 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002739 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002740 return;
2741 }
2742 // We treat a constructor like a non-member function, since its object
2743 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002744 }
2745
Douglas Gregorff7028a2009-11-13 23:59:09 +00002746 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002747 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002748
Douglas Gregor27381f32009-11-23 12:27:39 +00002749 // Overload resolution is always an unevaluated context.
2750 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2751
Douglas Gregorffe14e32009-11-14 01:20:54 +00002752 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2753 // C++ [class.copy]p3:
2754 // A member function template is never instantiated to perform the copy
2755 // of a class object to an object of its class type.
2756 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2757 if (NumArgs == 1 &&
2758 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002759 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2760 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002761 return;
2762 }
2763
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002764 // Add this candidate
2765 CandidateSet.push_back(OverloadCandidate());
2766 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002767 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002768 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002769 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002770 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002771 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002772
2773 unsigned NumArgsInProto = Proto->getNumArgs();
2774
2775 // (C++ 13.3.2p2): A candidate function having fewer than m
2776 // parameters is viable only if it has an ellipsis in its parameter
2777 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002778 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2779 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002780 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002781 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002782 return;
2783 }
2784
2785 // (C++ 13.3.2p2): A candidate function having more than m parameters
2786 // is viable only if the (m+1)st parameter has a default argument
2787 // (8.3.6). For the purposes of overload resolution, the
2788 // parameter list is truncated on the right, so that there are
2789 // exactly m parameters.
2790 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002791 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002792 // Not enough arguments.
2793 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002794 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002795 return;
2796 }
2797
2798 // Determine the implicit conversion sequences for each of the
2799 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002800 Candidate.Conversions.resize(NumArgs);
2801 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2802 if (ArgIdx < NumArgsInProto) {
2803 // (C++ 13.3.2p3): for F to be a viable function, there shall
2804 // exist for each argument an implicit conversion sequence
2805 // (13.3.3.1) that converts that argument to the corresponding
2806 // parameter of F.
2807 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002808 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002809 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002810 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00002811 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002812 if (Candidate.Conversions[ArgIdx].isBad()) {
2813 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002814 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002815 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002816 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002817 } else {
2818 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2819 // argument for which there is no corresponding parameter is
2820 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002821 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002822 }
2823 }
2824}
2825
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002826/// \brief Add all of the function declarations in the given function set to
2827/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002828void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002829 Expr **Args, unsigned NumArgs,
2830 OverloadCandidateSet& CandidateSet,
2831 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002832 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00002833 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2834 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002835 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002836 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002837 cast<CXXMethodDecl>(FD)->getParent(),
2838 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002839 CandidateSet, SuppressUserConversions);
2840 else
John McCalla0296f72010-03-19 07:35:19 +00002841 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002842 SuppressUserConversions);
2843 } else {
John McCalla0296f72010-03-19 07:35:19 +00002844 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002845 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2846 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002847 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002848 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002849 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002850 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002851 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002852 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002853 else
John McCalla0296f72010-03-19 07:35:19 +00002854 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00002855 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002856 Args, NumArgs, CandidateSet,
2857 SuppressUserConversions);
2858 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002859 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002860}
2861
John McCallf0f1cf02009-11-17 07:50:12 +00002862/// AddMethodCandidate - Adds a named decl (which is some kind of
2863/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00002864void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002865 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002866 Expr **Args, unsigned NumArgs,
2867 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002868 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00002869 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002870 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002871
2872 if (isa<UsingShadowDecl>(Decl))
2873 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2874
2875 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2876 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2877 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00002878 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2879 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002880 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002881 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002882 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002883 } else {
John McCalla0296f72010-03-19 07:35:19 +00002884 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002885 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002886 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002887 }
2888}
2889
Douglas Gregor436424c2008-11-18 23:14:02 +00002890/// AddMethodCandidate - Adds the given C++ member function to the set
2891/// of candidate functions, using the given function call arguments
2892/// and the object argument (@c Object). For example, in a call
2893/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2894/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2895/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00002896/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00002897void
John McCalla0296f72010-03-19 07:35:19 +00002898Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002899 CXXRecordDecl *ActingContext, QualType ObjectType,
2900 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002901 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002902 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002903 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002904 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002905 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002906 assert(!isa<CXXConstructorDecl>(Method) &&
2907 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002908
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002909 if (!CandidateSet.isNewCandidate(Method))
2910 return;
2911
Douglas Gregor27381f32009-11-23 12:27:39 +00002912 // Overload resolution is always an unevaluated context.
2913 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2914
Douglas Gregor436424c2008-11-18 23:14:02 +00002915 // Add this candidate
2916 CandidateSet.push_back(OverloadCandidate());
2917 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002918 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00002919 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002920 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002921 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002922
2923 unsigned NumArgsInProto = Proto->getNumArgs();
2924
2925 // (C++ 13.3.2p2): A candidate function having fewer than m
2926 // parameters is viable only if it has an ellipsis in its parameter
2927 // list (8.3.5).
2928 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2929 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002930 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002931 return;
2932 }
2933
2934 // (C++ 13.3.2p2): A candidate function having more than m parameters
2935 // is viable only if the (m+1)st parameter has a default argument
2936 // (8.3.6). For the purposes of overload resolution, the
2937 // parameter list is truncated on the right, so that there are
2938 // exactly m parameters.
2939 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2940 if (NumArgs < MinRequiredArgs) {
2941 // Not enough arguments.
2942 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002943 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002944 return;
2945 }
2946
2947 Candidate.Viable = true;
2948 Candidate.Conversions.resize(NumArgs + 1);
2949
John McCall6e9f8f62009-12-03 04:06:58 +00002950 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002951 // The implicit object argument is ignored.
2952 Candidate.IgnoreObjectArgument = true;
2953 else {
2954 // Determine the implicit conversion sequence for the object
2955 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002956 Candidate.Conversions[0]
2957 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002958 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002959 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002960 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002961 return;
2962 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002963 }
2964
2965 // Determine the implicit conversion sequences for each of the
2966 // arguments.
2967 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2968 if (ArgIdx < NumArgsInProto) {
2969 // (C++ 13.3.2p3): for F to be a viable function, there shall
2970 // exist for each argument an implicit conversion sequence
2971 // (13.3.3.1) that converts that argument to the corresponding
2972 // parameter of F.
2973 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002974 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002975 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002976 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00002977 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002978 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002979 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002980 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002981 break;
2982 }
2983 } else {
2984 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2985 // argument for which there is no corresponding parameter is
2986 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002987 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002988 }
2989 }
2990}
2991
Douglas Gregor97628d62009-08-21 00:16:32 +00002992/// \brief Add a C++ member function template as a candidate to the candidate
2993/// set, using template argument deduction to produce an appropriate member
2994/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002995void
Douglas Gregor97628d62009-08-21 00:16:32 +00002996Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00002997 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002998 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002999 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003000 QualType ObjectType,
3001 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003002 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003003 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003004 if (!CandidateSet.isNewCandidate(MethodTmpl))
3005 return;
3006
Douglas Gregor97628d62009-08-21 00:16:32 +00003007 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003008 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003009 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003010 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003011 // candidate functions in the usual way.113) A given name can refer to one
3012 // or more function templates and also to a set of overloaded non-template
3013 // functions. In such a case, the candidate functions generated from each
3014 // function template are combined with the set of non-template candidate
3015 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003016 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003017 FunctionDecl *Specialization = 0;
3018 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003019 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003020 Args, NumArgs, Specialization, Info)) {
3021 // FIXME: Record what happened with template argument deduction, so
3022 // that we can give the user a beautiful diagnostic.
3023 (void)Result;
3024 return;
3025 }
Mike Stump11289f42009-09-09 15:08:12 +00003026
Douglas Gregor97628d62009-08-21 00:16:32 +00003027 // Add the function template specialization produced by template argument
3028 // deduction as a candidate.
3029 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003030 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003031 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003032 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003033 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003034 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003035}
3036
Douglas Gregor05155d82009-08-21 23:19:43 +00003037/// \brief Add a C++ function template specialization as a candidate
3038/// in the candidate set, using template argument deduction to produce
3039/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003040void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003041Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003042 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003043 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003044 Expr **Args, unsigned NumArgs,
3045 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003046 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003047 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3048 return;
3049
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003050 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003051 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003052 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003053 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003054 // candidate functions in the usual way.113) A given name can refer to one
3055 // or more function templates and also to a set of overloaded non-template
3056 // functions. In such a case, the candidate functions generated from each
3057 // function template are combined with the set of non-template candidate
3058 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003059 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003060 FunctionDecl *Specialization = 0;
3061 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003062 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003063 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003064 CandidateSet.push_back(OverloadCandidate());
3065 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003066 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003067 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3068 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003069 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003070 Candidate.IsSurrogate = false;
3071 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00003072
3073 // TODO: record more information about failed template arguments
3074 Candidate.DeductionFailure.Result = Result;
3075 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003076 return;
3077 }
Mike Stump11289f42009-09-09 15:08:12 +00003078
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003079 // Add the function template specialization produced by template argument
3080 // deduction as a candidate.
3081 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003082 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003083 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003084}
Mike Stump11289f42009-09-09 15:08:12 +00003085
Douglas Gregora1f013e2008-11-07 22:36:19 +00003086/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003087/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003088/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003089/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003090/// (which may or may not be the same type as the type that the
3091/// conversion function produces).
3092void
3093Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003094 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003095 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003096 Expr *From, QualType ToType,
3097 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003098 assert(!Conversion->getDescribedFunctionTemplate() &&
3099 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003100 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003101 if (!CandidateSet.isNewCandidate(Conversion))
3102 return;
3103
Douglas Gregor27381f32009-11-23 12:27:39 +00003104 // Overload resolution is always an unevaluated context.
3105 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3106
Douglas Gregora1f013e2008-11-07 22:36:19 +00003107 // Add this candidate
3108 CandidateSet.push_back(OverloadCandidate());
3109 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003110 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003111 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003112 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003113 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003114 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003115 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003116 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003117
Douglas Gregor436424c2008-11-18 23:14:02 +00003118 // Determine the implicit conversion sequence for the implicit
3119 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003120 Candidate.Viable = true;
3121 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003122 Candidate.Conversions[0]
3123 = TryObjectArgumentInitialization(From->getType(), Conversion,
3124 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003125 // Conversion functions to a different type in the base class is visible in
3126 // the derived class. So, a derived to base conversion should not participate
3127 // in overload resolution.
3128 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3129 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003130 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003131 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003132 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003133 return;
3134 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003135
3136 // We won't go through a user-define type conversion function to convert a
3137 // derived to base as such conversions are given Conversion Rank. They only
3138 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3139 QualType FromCanon
3140 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3141 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3142 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3143 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003144 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003145 return;
3146 }
3147
Douglas Gregora1f013e2008-11-07 22:36:19 +00003148 // To determine what the conversion from the result of calling the
3149 // conversion function to the type we're eventually trying to
3150 // convert to (ToType), we need to synthesize a call to the
3151 // conversion function and attempt copy initialization from it. This
3152 // makes sure that we get the right semantics with respect to
3153 // lvalues/rvalues and the type. Fortunately, we can allocate this
3154 // call on the stack and we don't need its arguments to be
3155 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003156 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003157 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003158 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003159 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00003160 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00003161
3162 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003163 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3164 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003165 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003166 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003167 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003168 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003169 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003170 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003171 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003172
John McCall0d1da222010-01-12 00:44:57 +00003173 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003174 case ImplicitConversionSequence::StandardConversion:
3175 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003176
3177 // C++ [over.ics.user]p3:
3178 // If the user-defined conversion is specified by a specialization of a
3179 // conversion function template, the second standard conversion sequence
3180 // shall have exact match rank.
3181 if (Conversion->getPrimaryTemplate() &&
3182 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3183 Candidate.Viable = false;
3184 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3185 }
3186
Douglas Gregora1f013e2008-11-07 22:36:19 +00003187 break;
3188
3189 case ImplicitConversionSequence::BadConversion:
3190 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003191 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003192 break;
3193
3194 default:
Mike Stump11289f42009-09-09 15:08:12 +00003195 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003196 "Can only end up with a standard conversion sequence or failure");
3197 }
3198}
3199
Douglas Gregor05155d82009-08-21 23:19:43 +00003200/// \brief Adds a conversion function template specialization
3201/// candidate to the overload set, using template argument deduction
3202/// to deduce the template arguments of the conversion function
3203/// template from the type that we are converting to (C++
3204/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003205void
Douglas Gregor05155d82009-08-21 23:19:43 +00003206Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003207 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003208 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003209 Expr *From, QualType ToType,
3210 OverloadCandidateSet &CandidateSet) {
3211 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3212 "Only conversion function templates permitted here");
3213
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003214 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3215 return;
3216
John McCallbc077cf2010-02-08 23:07:23 +00003217 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003218 CXXConversionDecl *Specialization = 0;
3219 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003220 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003221 Specialization, Info)) {
3222 // FIXME: Record what happened with template argument deduction, so
3223 // that we can give the user a beautiful diagnostic.
3224 (void)Result;
3225 return;
3226 }
Mike Stump11289f42009-09-09 15:08:12 +00003227
Douglas Gregor05155d82009-08-21 23:19:43 +00003228 // Add the conversion function template specialization produced by
3229 // template argument deduction as a candidate.
3230 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003231 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003232 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003233}
3234
Douglas Gregorab7897a2008-11-19 22:57:39 +00003235/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3236/// converts the given @c Object to a function pointer via the
3237/// conversion function @c Conversion, and then attempts to call it
3238/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3239/// the type of function that we'll eventually be calling.
3240void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003241 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003242 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003243 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003244 QualType ObjectType,
3245 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003246 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003247 if (!CandidateSet.isNewCandidate(Conversion))
3248 return;
3249
Douglas Gregor27381f32009-11-23 12:27:39 +00003250 // Overload resolution is always an unevaluated context.
3251 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3252
Douglas Gregorab7897a2008-11-19 22:57:39 +00003253 CandidateSet.push_back(OverloadCandidate());
3254 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003255 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003256 Candidate.Function = 0;
3257 Candidate.Surrogate = Conversion;
3258 Candidate.Viable = true;
3259 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003260 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003261 Candidate.Conversions.resize(NumArgs + 1);
3262
3263 // Determine the implicit conversion sequence for the implicit
3264 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003265 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003266 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003267 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003268 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003269 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003270 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003271 return;
3272 }
3273
3274 // The first conversion is actually a user-defined conversion whose
3275 // first conversion is ObjectInit's standard conversion (which is
3276 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003277 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003278 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003279 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003280 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003281 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003282 = Candidate.Conversions[0].UserDefined.Before;
3283 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3284
Mike Stump11289f42009-09-09 15:08:12 +00003285 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003286 unsigned NumArgsInProto = Proto->getNumArgs();
3287
3288 // (C++ 13.3.2p2): A candidate function having fewer than m
3289 // parameters is viable only if it has an ellipsis in its parameter
3290 // list (8.3.5).
3291 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3292 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003293 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003294 return;
3295 }
3296
3297 // Function types don't have any default arguments, so just check if
3298 // we have enough arguments.
3299 if (NumArgs < NumArgsInProto) {
3300 // Not enough arguments.
3301 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003302 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003303 return;
3304 }
3305
3306 // Determine the implicit conversion sequences for each of the
3307 // arguments.
3308 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3309 if (ArgIdx < NumArgsInProto) {
3310 // (C++ 13.3.2p3): for F to be a viable function, there shall
3311 // exist for each argument an implicit conversion sequence
3312 // (13.3.3.1) that converts that argument to the corresponding
3313 // parameter of F.
3314 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003315 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003316 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003317 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003318 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003319 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003320 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003321 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003322 break;
3323 }
3324 } else {
3325 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3326 // argument for which there is no corresponding parameter is
3327 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003328 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003329 }
3330 }
3331}
3332
Mike Stump87c57ac2009-05-16 07:39:55 +00003333// FIXME: This will eventually be removed, once we've migrated all of the
3334// operator overloading logic over to the scheme used by binary operators, which
3335// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003336void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003337 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003338 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003339 OverloadCandidateSet& CandidateSet,
3340 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003341 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003342
3343 QualType T1 = Args[0]->getType();
3344 QualType T2;
3345 if (NumArgs > 1)
3346 T2 = Args[1]->getType();
3347
3348 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003349 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003350 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3351 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3352 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3353 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003354 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003355 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003356}
3357
3358/// \brief Add overload candidates for overloaded operators that are
3359/// member functions.
3360///
3361/// Add the overloaded operator candidates that are member functions
3362/// for the operator Op that was used in an operator expression such
3363/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3364/// CandidateSet will store the added overload candidates. (C++
3365/// [over.match.oper]).
3366void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3367 SourceLocation OpLoc,
3368 Expr **Args, unsigned NumArgs,
3369 OverloadCandidateSet& CandidateSet,
3370 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003371 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3372
3373 // C++ [over.match.oper]p3:
3374 // For a unary operator @ with an operand of a type whose
3375 // cv-unqualified version is T1, and for a binary operator @ with
3376 // a left operand of a type whose cv-unqualified version is T1 and
3377 // a right operand of a type whose cv-unqualified version is T2,
3378 // three sets of candidate functions, designated member
3379 // candidates, non-member candidates and built-in candidates, are
3380 // constructed as follows:
3381 QualType T1 = Args[0]->getType();
3382 QualType T2;
3383 if (NumArgs > 1)
3384 T2 = Args[1]->getType();
3385
3386 // -- If T1 is a class type, the set of member candidates is the
3387 // result of the qualified lookup of T1::operator@
3388 // (13.3.1.1.1); otherwise, the set of member candidates is
3389 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003390 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003391 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003392 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003393 return;
Mike Stump11289f42009-09-09 15:08:12 +00003394
John McCall27b18f82009-11-17 02:14:36 +00003395 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3396 LookupQualifiedName(Operators, T1Rec->getDecl());
3397 Operators.suppressDiagnostics();
3398
Mike Stump11289f42009-09-09 15:08:12 +00003399 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003400 OperEnd = Operators.end();
3401 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003402 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003403 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003404 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003405 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003406 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003407}
3408
Douglas Gregora11693b2008-11-12 17:17:38 +00003409/// AddBuiltinCandidate - Add a candidate for a built-in
3410/// operator. ResultTy and ParamTys are the result and parameter types
3411/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003412/// arguments being passed to the candidate. IsAssignmentOperator
3413/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003414/// operator. NumContextualBoolArguments is the number of arguments
3415/// (at the beginning of the argument list) that will be contextually
3416/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003417void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003418 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003419 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003420 bool IsAssignmentOperator,
3421 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003422 // Overload resolution is always an unevaluated context.
3423 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3424
Douglas Gregora11693b2008-11-12 17:17:38 +00003425 // Add this candidate
3426 CandidateSet.push_back(OverloadCandidate());
3427 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003428 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003429 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003430 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003431 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003432 Candidate.BuiltinTypes.ResultTy = ResultTy;
3433 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3434 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3435
3436 // Determine the implicit conversion sequences for each of the
3437 // arguments.
3438 Candidate.Viable = true;
3439 Candidate.Conversions.resize(NumArgs);
3440 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003441 // C++ [over.match.oper]p4:
3442 // For the built-in assignment operators, conversions of the
3443 // left operand are restricted as follows:
3444 // -- no temporaries are introduced to hold the left operand, and
3445 // -- no user-defined conversions are applied to the left
3446 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003447 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003448 //
3449 // We block these conversions by turning off user-defined
3450 // conversions, since that is the only way that initialization of
3451 // a reference to a non-class type can occur from something that
3452 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003453 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003454 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003455 "Contextual conversion to bool requires bool type");
3456 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3457 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003458 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003459 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003460 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003461 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003462 }
John McCall0d1da222010-01-12 00:44:57 +00003463 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003464 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003465 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003466 break;
3467 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003468 }
3469}
3470
3471/// BuiltinCandidateTypeSet - A set of types that will be used for the
3472/// candidate operator functions for built-in operators (C++
3473/// [over.built]). The types are separated into pointer types and
3474/// enumeration types.
3475class BuiltinCandidateTypeSet {
3476 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003477 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003478
3479 /// PointerTypes - The set of pointer types that will be used in the
3480 /// built-in candidates.
3481 TypeSet PointerTypes;
3482
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003483 /// MemberPointerTypes - The set of member pointer types that will be
3484 /// used in the built-in candidates.
3485 TypeSet MemberPointerTypes;
3486
Douglas Gregora11693b2008-11-12 17:17:38 +00003487 /// EnumerationTypes - The set of enumeration types that will be
3488 /// used in the built-in candidates.
3489 TypeSet EnumerationTypes;
3490
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003491 /// Sema - The semantic analysis instance where we are building the
3492 /// candidate type set.
3493 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003494
Douglas Gregora11693b2008-11-12 17:17:38 +00003495 /// Context - The AST context in which we will build the type sets.
3496 ASTContext &Context;
3497
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003498 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3499 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003500 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003501
3502public:
3503 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003504 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003505
Mike Stump11289f42009-09-09 15:08:12 +00003506 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003507 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003508
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003509 void AddTypesConvertedFrom(QualType Ty,
3510 SourceLocation Loc,
3511 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003512 bool AllowExplicitConversions,
3513 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003514
3515 /// pointer_begin - First pointer type found;
3516 iterator pointer_begin() { return PointerTypes.begin(); }
3517
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003518 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003519 iterator pointer_end() { return PointerTypes.end(); }
3520
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003521 /// member_pointer_begin - First member pointer type found;
3522 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3523
3524 /// member_pointer_end - Past the last member pointer type found;
3525 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3526
Douglas Gregora11693b2008-11-12 17:17:38 +00003527 /// enumeration_begin - First enumeration type found;
3528 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3529
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003530 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003531 iterator enumeration_end() { return EnumerationTypes.end(); }
3532};
3533
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003534/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003535/// the set of pointer types along with any more-qualified variants of
3536/// that type. For example, if @p Ty is "int const *", this routine
3537/// will add "int const *", "int const volatile *", "int const
3538/// restrict *", and "int const volatile restrict *" to the set of
3539/// pointer types. Returns true if the add of @p Ty itself succeeded,
3540/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003541///
3542/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003543bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003544BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3545 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003546
Douglas Gregora11693b2008-11-12 17:17:38 +00003547 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003548 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003549 return false;
3550
John McCall8ccfcb52009-09-24 19:53:00 +00003551 const PointerType *PointerTy = Ty->getAs<PointerType>();
3552 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003553
John McCall8ccfcb52009-09-24 19:53:00 +00003554 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003555 // Don't add qualified variants of arrays. For one, they're not allowed
3556 // (the qualifier would sink to the element type), and for another, the
3557 // only overload situation where it matters is subscript or pointer +- int,
3558 // and those shouldn't have qualifier variants anyway.
3559 if (PointeeTy->isArrayType())
3560 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003561 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003562 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003563 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003564 bool hasVolatile = VisibleQuals.hasVolatile();
3565 bool hasRestrict = VisibleQuals.hasRestrict();
3566
John McCall8ccfcb52009-09-24 19:53:00 +00003567 // Iterate through all strict supersets of BaseCVR.
3568 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3569 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003570 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3571 // in the types.
3572 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3573 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003574 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3575 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003576 }
3577
3578 return true;
3579}
3580
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003581/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3582/// to the set of pointer types along with any more-qualified variants of
3583/// that type. For example, if @p Ty is "int const *", this routine
3584/// will add "int const *", "int const volatile *", "int const
3585/// restrict *", and "int const volatile restrict *" to the set of
3586/// pointer types. Returns true if the add of @p Ty itself succeeded,
3587/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003588///
3589/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003590bool
3591BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3592 QualType Ty) {
3593 // Insert this type.
3594 if (!MemberPointerTypes.insert(Ty))
3595 return false;
3596
John McCall8ccfcb52009-09-24 19:53:00 +00003597 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3598 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003599
John McCall8ccfcb52009-09-24 19:53:00 +00003600 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003601 // Don't add qualified variants of arrays. For one, they're not allowed
3602 // (the qualifier would sink to the element type), and for another, the
3603 // only overload situation where it matters is subscript or pointer +- int,
3604 // and those shouldn't have qualifier variants anyway.
3605 if (PointeeTy->isArrayType())
3606 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003607 const Type *ClassTy = PointerTy->getClass();
3608
3609 // Iterate through all strict supersets of the pointee type's CVR
3610 // qualifiers.
3611 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3612 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3613 if ((CVR | BaseCVR) != CVR) continue;
3614
3615 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3616 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003617 }
3618
3619 return true;
3620}
3621
Douglas Gregora11693b2008-11-12 17:17:38 +00003622/// AddTypesConvertedFrom - Add each of the types to which the type @p
3623/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003624/// primarily interested in pointer types and enumeration types. We also
3625/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003626/// AllowUserConversions is true if we should look at the conversion
3627/// functions of a class type, and AllowExplicitConversions if we
3628/// should also include the explicit conversion functions of a class
3629/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003630void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003631BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003632 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003633 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003634 bool AllowExplicitConversions,
3635 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003636 // Only deal with canonical types.
3637 Ty = Context.getCanonicalType(Ty);
3638
3639 // Look through reference types; they aren't part of the type of an
3640 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003641 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003642 Ty = RefTy->getPointeeType();
3643
3644 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003645 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003646
Sebastian Redl65ae2002009-11-05 16:36:20 +00003647 // If we're dealing with an array type, decay to the pointer.
3648 if (Ty->isArrayType())
3649 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3650
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003651 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003652 QualType PointeeTy = PointerTy->getPointeeType();
3653
3654 // Insert our type, and its more-qualified variants, into the set
3655 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003656 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003657 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003658 } else if (Ty->isMemberPointerType()) {
3659 // Member pointers are far easier, since the pointee can't be converted.
3660 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3661 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003662 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003663 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003664 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003665 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003666 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003667 // No conversion functions in incomplete types.
3668 return;
3669 }
Mike Stump11289f42009-09-09 15:08:12 +00003670
Douglas Gregora11693b2008-11-12 17:17:38 +00003671 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003672 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003673 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003674 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003675 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003676 NamedDecl *D = I.getDecl();
3677 if (isa<UsingShadowDecl>(D))
3678 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003679
Mike Stump11289f42009-09-09 15:08:12 +00003680 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003681 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003682 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003683 continue;
3684
John McCallda4458e2010-03-31 01:36:47 +00003685 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003686 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003687 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003688 VisibleQuals);
3689 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003690 }
3691 }
3692 }
3693}
3694
Douglas Gregor84605ae2009-08-24 13:43:27 +00003695/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3696/// the volatile- and non-volatile-qualified assignment operators for the
3697/// given type to the candidate set.
3698static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3699 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003700 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003701 unsigned NumArgs,
3702 OverloadCandidateSet &CandidateSet) {
3703 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregor84605ae2009-08-24 13:43:27 +00003705 // T& operator=(T&, T)
3706 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3707 ParamTypes[1] = T;
3708 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3709 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003710
Douglas Gregor84605ae2009-08-24 13:43:27 +00003711 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3712 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003713 ParamTypes[0]
3714 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003715 ParamTypes[1] = T;
3716 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003717 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003718 }
3719}
Mike Stump11289f42009-09-09 15:08:12 +00003720
Sebastian Redl1054fae2009-10-25 17:03:50 +00003721/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3722/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003723static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3724 Qualifiers VRQuals;
3725 const RecordType *TyRec;
3726 if (const MemberPointerType *RHSMPType =
3727 ArgExpr->getType()->getAs<MemberPointerType>())
3728 TyRec = cast<RecordType>(RHSMPType->getClass());
3729 else
3730 TyRec = ArgExpr->getType()->getAs<RecordType>();
3731 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003732 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003733 VRQuals.addVolatile();
3734 VRQuals.addRestrict();
3735 return VRQuals;
3736 }
3737
3738 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003739 if (!ClassDecl->hasDefinition())
3740 return VRQuals;
3741
John McCallad371252010-01-20 00:46:10 +00003742 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003743 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003744
John McCallad371252010-01-20 00:46:10 +00003745 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003746 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003747 NamedDecl *D = I.getDecl();
3748 if (isa<UsingShadowDecl>(D))
3749 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3750 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003751 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3752 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3753 CanTy = ResTypeRef->getPointeeType();
3754 // Need to go down the pointer/mempointer chain and add qualifiers
3755 // as see them.
3756 bool done = false;
3757 while (!done) {
3758 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3759 CanTy = ResTypePtr->getPointeeType();
3760 else if (const MemberPointerType *ResTypeMPtr =
3761 CanTy->getAs<MemberPointerType>())
3762 CanTy = ResTypeMPtr->getPointeeType();
3763 else
3764 done = true;
3765 if (CanTy.isVolatileQualified())
3766 VRQuals.addVolatile();
3767 if (CanTy.isRestrictQualified())
3768 VRQuals.addRestrict();
3769 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3770 return VRQuals;
3771 }
3772 }
3773 }
3774 return VRQuals;
3775}
3776
Douglas Gregord08452f2008-11-19 15:42:04 +00003777/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3778/// operator overloads to the candidate set (C++ [over.built]), based
3779/// on the operator @p Op and the arguments given. For example, if the
3780/// operator is a binary '+', this routine might add "int
3781/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003782void
Mike Stump11289f42009-09-09 15:08:12 +00003783Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003784 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003785 Expr **Args, unsigned NumArgs,
3786 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003787 // The set of "promoted arithmetic types", which are the arithmetic
3788 // types are that preserved by promotion (C++ [over.built]p2). Note
3789 // that the first few of these types are the promoted integral
3790 // types; these types need to be first.
3791 // FIXME: What about complex?
3792 const unsigned FirstIntegralType = 0;
3793 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003794 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003795 LastPromotedIntegralType = 13;
3796 const unsigned FirstPromotedArithmeticType = 7,
3797 LastPromotedArithmeticType = 16;
3798 const unsigned NumArithmeticTypes = 16;
3799 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003800 Context.BoolTy, Context.CharTy, Context.WCharTy,
3801// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003802 Context.SignedCharTy, Context.ShortTy,
3803 Context.UnsignedCharTy, Context.UnsignedShortTy,
3804 Context.IntTy, Context.LongTy, Context.LongLongTy,
3805 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3806 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3807 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003808 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3809 "Invalid first promoted integral type");
3810 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3811 == Context.UnsignedLongLongTy &&
3812 "Invalid last promoted integral type");
3813 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3814 "Invalid first promoted arithmetic type");
3815 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3816 == Context.LongDoubleTy &&
3817 "Invalid last promoted arithmetic type");
3818
Douglas Gregora11693b2008-11-12 17:17:38 +00003819 // Find all of the types that the arguments can convert to, but only
3820 // if the operator we're looking at has built-in operator candidates
3821 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003822 Qualifiers VisibleTypeConversionsQuals;
3823 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003824 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3825 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3826
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003827 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003828 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3829 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003830 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003831 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003832 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003833 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003834 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003835 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003836 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003837 true,
3838 (Op == OO_Exclaim ||
3839 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003840 Op == OO_PipePipe),
3841 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003842 }
3843
3844 bool isComparison = false;
3845 switch (Op) {
3846 case OO_None:
3847 case NUM_OVERLOADED_OPERATORS:
3848 assert(false && "Expected an overloaded operator");
3849 break;
3850
Douglas Gregord08452f2008-11-19 15:42:04 +00003851 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003852 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003853 goto UnaryStar;
3854 else
3855 goto BinaryStar;
3856 break;
3857
3858 case OO_Plus: // '+' is either unary or binary
3859 if (NumArgs == 1)
3860 goto UnaryPlus;
3861 else
3862 goto BinaryPlus;
3863 break;
3864
3865 case OO_Minus: // '-' is either unary or binary
3866 if (NumArgs == 1)
3867 goto UnaryMinus;
3868 else
3869 goto BinaryMinus;
3870 break;
3871
3872 case OO_Amp: // '&' is either unary or binary
3873 if (NumArgs == 1)
3874 goto UnaryAmp;
3875 else
3876 goto BinaryAmp;
3877
3878 case OO_PlusPlus:
3879 case OO_MinusMinus:
3880 // C++ [over.built]p3:
3881 //
3882 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3883 // is either volatile or empty, there exist candidate operator
3884 // functions of the form
3885 //
3886 // VQ T& operator++(VQ T&);
3887 // T operator++(VQ T&, int);
3888 //
3889 // C++ [over.built]p4:
3890 //
3891 // For every pair (T, VQ), where T is an arithmetic type other
3892 // than bool, and VQ is either volatile or empty, there exist
3893 // candidate operator functions of the form
3894 //
3895 // VQ T& operator--(VQ T&);
3896 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003897 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003898 Arith < NumArithmeticTypes; ++Arith) {
3899 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003900 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003901 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003902
3903 // Non-volatile version.
3904 if (NumArgs == 1)
3905 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3906 else
3907 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003908 // heuristic to reduce number of builtin candidates in the set.
3909 // Add volatile version only if there are conversions to a volatile type.
3910 if (VisibleTypeConversionsQuals.hasVolatile()) {
3911 // Volatile version
3912 ParamTypes[0]
3913 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3914 if (NumArgs == 1)
3915 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3916 else
3917 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3918 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003919 }
3920
3921 // C++ [over.built]p5:
3922 //
3923 // For every pair (T, VQ), where T is a cv-qualified or
3924 // cv-unqualified object type, and VQ is either volatile or
3925 // empty, there exist candidate operator functions of the form
3926 //
3927 // T*VQ& operator++(T*VQ&);
3928 // T*VQ& operator--(T*VQ&);
3929 // T* operator++(T*VQ&, int);
3930 // T* operator--(T*VQ&, int);
3931 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3932 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3933 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003934 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003935 continue;
3936
Mike Stump11289f42009-09-09 15:08:12 +00003937 QualType ParamTypes[2] = {
3938 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003939 };
Mike Stump11289f42009-09-09 15:08:12 +00003940
Douglas Gregord08452f2008-11-19 15:42:04 +00003941 // Without volatile
3942 if (NumArgs == 1)
3943 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3944 else
3945 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3946
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003947 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3948 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003949 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003950 ParamTypes[0]
3951 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003952 if (NumArgs == 1)
3953 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3954 else
3955 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3956 }
3957 }
3958 break;
3959
3960 UnaryStar:
3961 // C++ [over.built]p6:
3962 // For every cv-qualified or cv-unqualified object type T, there
3963 // exist candidate operator functions of the form
3964 //
3965 // T& operator*(T*);
3966 //
3967 // C++ [over.built]p7:
3968 // For every function type T, there exist candidate operator
3969 // functions of the form
3970 // T& operator*(T*);
3971 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3972 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3973 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003974 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003975 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003976 &ParamTy, Args, 1, CandidateSet);
3977 }
3978 break;
3979
3980 UnaryPlus:
3981 // C++ [over.built]p8:
3982 // For every type T, there exist candidate operator functions of
3983 // the form
3984 //
3985 // T* operator+(T*);
3986 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3987 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3988 QualType ParamTy = *Ptr;
3989 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3990 }
Mike Stump11289f42009-09-09 15:08:12 +00003991
Douglas Gregord08452f2008-11-19 15:42:04 +00003992 // Fall through
3993
3994 UnaryMinus:
3995 // C++ [over.built]p9:
3996 // For every promoted arithmetic type T, there exist candidate
3997 // operator functions of the form
3998 //
3999 // T operator+(T);
4000 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004001 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004002 Arith < LastPromotedArithmeticType; ++Arith) {
4003 QualType ArithTy = ArithmeticTypes[Arith];
4004 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4005 }
4006 break;
4007
4008 case OO_Tilde:
4009 // C++ [over.built]p10:
4010 // For every promoted integral type T, there exist candidate
4011 // operator functions of the form
4012 //
4013 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004014 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004015 Int < LastPromotedIntegralType; ++Int) {
4016 QualType IntTy = ArithmeticTypes[Int];
4017 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4018 }
4019 break;
4020
Douglas Gregora11693b2008-11-12 17:17:38 +00004021 case OO_New:
4022 case OO_Delete:
4023 case OO_Array_New:
4024 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004025 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004026 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004027 break;
4028
4029 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004030 UnaryAmp:
4031 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004032 // C++ [over.match.oper]p3:
4033 // -- For the operator ',', the unary operator '&', or the
4034 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004035 break;
4036
Douglas Gregor84605ae2009-08-24 13:43:27 +00004037 case OO_EqualEqual:
4038 case OO_ExclaimEqual:
4039 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004040 // For every pointer to member type T, there exist candidate operator
4041 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004042 //
4043 // bool operator==(T,T);
4044 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004045 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004046 MemPtr = CandidateTypes.member_pointer_begin(),
4047 MemPtrEnd = CandidateTypes.member_pointer_end();
4048 MemPtr != MemPtrEnd;
4049 ++MemPtr) {
4050 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4051 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4052 }
Mike Stump11289f42009-09-09 15:08:12 +00004053
Douglas Gregor84605ae2009-08-24 13:43:27 +00004054 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004055
Douglas Gregora11693b2008-11-12 17:17:38 +00004056 case OO_Less:
4057 case OO_Greater:
4058 case OO_LessEqual:
4059 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004060 // C++ [over.built]p15:
4061 //
4062 // For every pointer or enumeration type T, there exist
4063 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004064 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004065 // bool operator<(T, T);
4066 // bool operator>(T, T);
4067 // bool operator<=(T, T);
4068 // bool operator>=(T, T);
4069 // bool operator==(T, T);
4070 // bool operator!=(T, T);
4071 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4072 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4073 QualType ParamTypes[2] = { *Ptr, *Ptr };
4074 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4075 }
Mike Stump11289f42009-09-09 15:08:12 +00004076 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004077 = CandidateTypes.enumeration_begin();
4078 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4079 QualType ParamTypes[2] = { *Enum, *Enum };
4080 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4081 }
4082
4083 // Fall through.
4084 isComparison = true;
4085
Douglas Gregord08452f2008-11-19 15:42:04 +00004086 BinaryPlus:
4087 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004088 if (!isComparison) {
4089 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4090
4091 // C++ [over.built]p13:
4092 //
4093 // For every cv-qualified or cv-unqualified object type T
4094 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004095 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004096 // T* operator+(T*, ptrdiff_t);
4097 // T& operator[](T*, ptrdiff_t); [BELOW]
4098 // T* operator-(T*, ptrdiff_t);
4099 // T* operator+(ptrdiff_t, T*);
4100 // T& operator[](ptrdiff_t, T*); [BELOW]
4101 //
4102 // C++ [over.built]p14:
4103 //
4104 // For every T, where T is a pointer to object type, there
4105 // exist candidate operator functions of the form
4106 //
4107 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004108 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004109 = CandidateTypes.pointer_begin();
4110 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4111 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4112
4113 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4114 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4115
4116 if (Op == OO_Plus) {
4117 // T* operator+(ptrdiff_t, T*);
4118 ParamTypes[0] = ParamTypes[1];
4119 ParamTypes[1] = *Ptr;
4120 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4121 } else {
4122 // ptrdiff_t operator-(T, T);
4123 ParamTypes[1] = *Ptr;
4124 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4125 Args, 2, CandidateSet);
4126 }
4127 }
4128 }
4129 // Fall through
4130
Douglas Gregora11693b2008-11-12 17:17:38 +00004131 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004132 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004133 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004134 // C++ [over.built]p12:
4135 //
4136 // For every pair of promoted arithmetic types L and R, there
4137 // exist candidate operator functions of the form
4138 //
4139 // LR operator*(L, R);
4140 // LR operator/(L, R);
4141 // LR operator+(L, R);
4142 // LR operator-(L, R);
4143 // bool operator<(L, R);
4144 // bool operator>(L, R);
4145 // bool operator<=(L, R);
4146 // bool operator>=(L, R);
4147 // bool operator==(L, R);
4148 // bool operator!=(L, R);
4149 //
4150 // where LR is the result of the usual arithmetic conversions
4151 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004152 //
4153 // C++ [over.built]p24:
4154 //
4155 // For every pair of promoted arithmetic types L and R, there exist
4156 // candidate operator functions of the form
4157 //
4158 // LR operator?(bool, L, R);
4159 //
4160 // where LR is the result of the usual arithmetic conversions
4161 // between types L and R.
4162 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004163 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004164 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004165 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004166 Right < LastPromotedArithmeticType; ++Right) {
4167 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004168 QualType Result
4169 = isComparison
4170 ? Context.BoolTy
4171 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004172 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4173 }
4174 }
4175 break;
4176
4177 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004178 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004179 case OO_Caret:
4180 case OO_Pipe:
4181 case OO_LessLess:
4182 case OO_GreaterGreater:
4183 // C++ [over.built]p17:
4184 //
4185 // For every pair of promoted integral types L and R, there
4186 // exist candidate operator functions of the form
4187 //
4188 // LR operator%(L, R);
4189 // LR operator&(L, R);
4190 // LR operator^(L, R);
4191 // LR operator|(L, R);
4192 // L operator<<(L, R);
4193 // L operator>>(L, R);
4194 //
4195 // where LR is the result of the usual arithmetic conversions
4196 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004197 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004198 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004199 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004200 Right < LastPromotedIntegralType; ++Right) {
4201 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4202 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4203 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004204 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004205 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4206 }
4207 }
4208 break;
4209
4210 case OO_Equal:
4211 // C++ [over.built]p20:
4212 //
4213 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004214 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004215 // empty, there exist candidate operator functions of the form
4216 //
4217 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004218 for (BuiltinCandidateTypeSet::iterator
4219 Enum = CandidateTypes.enumeration_begin(),
4220 EnumEnd = CandidateTypes.enumeration_end();
4221 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004222 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004223 CandidateSet);
4224 for (BuiltinCandidateTypeSet::iterator
4225 MemPtr = CandidateTypes.member_pointer_begin(),
4226 MemPtrEnd = CandidateTypes.member_pointer_end();
4227 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004228 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004229 CandidateSet);
4230 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004231
4232 case OO_PlusEqual:
4233 case OO_MinusEqual:
4234 // C++ [over.built]p19:
4235 //
4236 // For every pair (T, VQ), where T is any type and VQ is either
4237 // volatile or empty, there exist candidate operator functions
4238 // of the form
4239 //
4240 // T*VQ& operator=(T*VQ&, T*);
4241 //
4242 // C++ [over.built]p21:
4243 //
4244 // For every pair (T, VQ), where T is a cv-qualified or
4245 // cv-unqualified object type and VQ is either volatile or
4246 // empty, there exist candidate operator functions of the form
4247 //
4248 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4249 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4250 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4251 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4252 QualType ParamTypes[2];
4253 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4254
4255 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004256 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004257 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4258 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004259
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004260 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4261 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004262 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004263 ParamTypes[0]
4264 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004265 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4266 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004267 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004268 }
4269 // Fall through.
4270
4271 case OO_StarEqual:
4272 case OO_SlashEqual:
4273 // C++ [over.built]p18:
4274 //
4275 // For every triple (L, VQ, R), where L is an arithmetic type,
4276 // VQ is either volatile or empty, and R is a promoted
4277 // arithmetic type, there exist candidate operator functions of
4278 // the form
4279 //
4280 // VQ L& operator=(VQ L&, R);
4281 // VQ L& operator*=(VQ L&, R);
4282 // VQ L& operator/=(VQ L&, R);
4283 // VQ L& operator+=(VQ L&, R);
4284 // VQ L& operator-=(VQ L&, R);
4285 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004286 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004287 Right < LastPromotedArithmeticType; ++Right) {
4288 QualType ParamTypes[2];
4289 ParamTypes[1] = ArithmeticTypes[Right];
4290
4291 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004292 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004293 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4294 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004295
4296 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004297 if (VisibleTypeConversionsQuals.hasVolatile()) {
4298 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4299 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4300 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4301 /*IsAssigmentOperator=*/Op == OO_Equal);
4302 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004303 }
4304 }
4305 break;
4306
4307 case OO_PercentEqual:
4308 case OO_LessLessEqual:
4309 case OO_GreaterGreaterEqual:
4310 case OO_AmpEqual:
4311 case OO_CaretEqual:
4312 case OO_PipeEqual:
4313 // C++ [over.built]p22:
4314 //
4315 // For every triple (L, VQ, R), where L is an integral type, VQ
4316 // is either volatile or empty, and R is a promoted integral
4317 // type, there exist candidate operator functions of the form
4318 //
4319 // VQ L& operator%=(VQ L&, R);
4320 // VQ L& operator<<=(VQ L&, R);
4321 // VQ L& operator>>=(VQ L&, R);
4322 // VQ L& operator&=(VQ L&, R);
4323 // VQ L& operator^=(VQ L&, R);
4324 // VQ L& operator|=(VQ L&, R);
4325 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004326 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004327 Right < LastPromotedIntegralType; ++Right) {
4328 QualType ParamTypes[2];
4329 ParamTypes[1] = ArithmeticTypes[Right];
4330
4331 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004332 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004333 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004334 if (VisibleTypeConversionsQuals.hasVolatile()) {
4335 // Add this built-in operator as a candidate (VQ is 'volatile').
4336 ParamTypes[0] = ArithmeticTypes[Left];
4337 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4338 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4339 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4340 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004341 }
4342 }
4343 break;
4344
Douglas Gregord08452f2008-11-19 15:42:04 +00004345 case OO_Exclaim: {
4346 // C++ [over.operator]p23:
4347 //
4348 // There also exist candidate operator functions of the form
4349 //
Mike Stump11289f42009-09-09 15:08:12 +00004350 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004351 // bool operator&&(bool, bool); [BELOW]
4352 // bool operator||(bool, bool); [BELOW]
4353 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004354 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4355 /*IsAssignmentOperator=*/false,
4356 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004357 break;
4358 }
4359
Douglas Gregora11693b2008-11-12 17:17:38 +00004360 case OO_AmpAmp:
4361 case OO_PipePipe: {
4362 // C++ [over.operator]p23:
4363 //
4364 // There also exist candidate operator functions of the form
4365 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004366 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004367 // bool operator&&(bool, bool);
4368 // bool operator||(bool, bool);
4369 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004370 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4371 /*IsAssignmentOperator=*/false,
4372 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004373 break;
4374 }
4375
4376 case OO_Subscript:
4377 // C++ [over.built]p13:
4378 //
4379 // For every cv-qualified or cv-unqualified object type T there
4380 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004381 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004382 // T* operator+(T*, ptrdiff_t); [ABOVE]
4383 // T& operator[](T*, ptrdiff_t);
4384 // T* operator-(T*, ptrdiff_t); [ABOVE]
4385 // T* operator+(ptrdiff_t, T*); [ABOVE]
4386 // T& operator[](ptrdiff_t, T*);
4387 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4388 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4389 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004390 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004391 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004392
4393 // T& operator[](T*, ptrdiff_t)
4394 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4395
4396 // T& operator[](ptrdiff_t, T*);
4397 ParamTypes[0] = ParamTypes[1];
4398 ParamTypes[1] = *Ptr;
4399 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4400 }
4401 break;
4402
4403 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004404 // C++ [over.built]p11:
4405 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4406 // C1 is the same type as C2 or is a derived class of C2, T is an object
4407 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4408 // there exist candidate operator functions of the form
4409 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4410 // where CV12 is the union of CV1 and CV2.
4411 {
4412 for (BuiltinCandidateTypeSet::iterator Ptr =
4413 CandidateTypes.pointer_begin();
4414 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4415 QualType C1Ty = (*Ptr);
4416 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004417 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004418 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004419 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004420 if (!isa<RecordType>(C1))
4421 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004422 // heuristic to reduce number of builtin candidates in the set.
4423 // Add volatile/restrict version only if there are conversions to a
4424 // volatile/restrict type.
4425 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4426 continue;
4427 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4428 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004429 }
4430 for (BuiltinCandidateTypeSet::iterator
4431 MemPtr = CandidateTypes.member_pointer_begin(),
4432 MemPtrEnd = CandidateTypes.member_pointer_end();
4433 MemPtr != MemPtrEnd; ++MemPtr) {
4434 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4435 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004436 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004437 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4438 break;
4439 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4440 // build CV12 T&
4441 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004442 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4443 T.isVolatileQualified())
4444 continue;
4445 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4446 T.isRestrictQualified())
4447 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004448 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004449 QualType ResultTy = Context.getLValueReferenceType(T);
4450 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4451 }
4452 }
4453 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004454 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004455
4456 case OO_Conditional:
4457 // Note that we don't consider the first argument, since it has been
4458 // contextually converted to bool long ago. The candidates below are
4459 // therefore added as binary.
4460 //
4461 // C++ [over.built]p24:
4462 // For every type T, where T is a pointer or pointer-to-member type,
4463 // there exist candidate operator functions of the form
4464 //
4465 // T operator?(bool, T, T);
4466 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004467 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4468 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4469 QualType ParamTypes[2] = { *Ptr, *Ptr };
4470 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4471 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004472 for (BuiltinCandidateTypeSet::iterator Ptr =
4473 CandidateTypes.member_pointer_begin(),
4474 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4475 QualType ParamTypes[2] = { *Ptr, *Ptr };
4476 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4477 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004478 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004479 }
4480}
4481
Douglas Gregore254f902009-02-04 00:32:51 +00004482/// \brief Add function candidates found via argument-dependent lookup
4483/// to the set of overloading candidates.
4484///
4485/// This routine performs argument-dependent name lookup based on the
4486/// given function name (which may also be an operator name) and adds
4487/// all of the overload candidates found by ADL to the overload
4488/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004489void
Douglas Gregore254f902009-02-04 00:32:51 +00004490Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004491 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004492 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004493 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004494 OverloadCandidateSet& CandidateSet,
4495 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004496 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004497
John McCall91f61fc2010-01-26 06:04:06 +00004498 // FIXME: This approach for uniquing ADL results (and removing
4499 // redundant candidates from the set) relies on pointer-equality,
4500 // which means we need to key off the canonical decl. However,
4501 // always going back to the canonical decl might not get us the
4502 // right set of default arguments. What default arguments are
4503 // we supposed to consider on ADL candidates, anyway?
4504
Douglas Gregorcabea402009-09-22 15:41:20 +00004505 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004506 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004507
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004508 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004509 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4510 CandEnd = CandidateSet.end();
4511 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004512 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004513 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004514 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004515 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004516 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004517
4518 // For each of the ADL candidates we found, add it to the overload
4519 // set.
John McCall8fe68082010-01-26 07:16:45 +00004520 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004521 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004522 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004523 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004524 continue;
4525
John McCalla0296f72010-03-19 07:35:19 +00004526 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004527 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004528 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004529 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004530 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004531 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004532 }
Douglas Gregore254f902009-02-04 00:32:51 +00004533}
4534
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004535/// isBetterOverloadCandidate - Determines whether the first overload
4536/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004537bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004538Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004539 const OverloadCandidate& Cand2,
4540 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004541 // Define viable functions to be better candidates than non-viable
4542 // functions.
4543 if (!Cand2.Viable)
4544 return Cand1.Viable;
4545 else if (!Cand1.Viable)
4546 return false;
4547
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004548 // C++ [over.match.best]p1:
4549 //
4550 // -- if F is a static member function, ICS1(F) is defined such
4551 // that ICS1(F) is neither better nor worse than ICS1(G) for
4552 // any function G, and, symmetrically, ICS1(G) is neither
4553 // better nor worse than ICS1(F).
4554 unsigned StartArg = 0;
4555 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4556 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004557
Douglas Gregord3cb3562009-07-07 23:38:56 +00004558 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004559 // A viable function F1 is defined to be a better function than another
4560 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004561 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004562 unsigned NumArgs = Cand1.Conversions.size();
4563 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4564 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004565 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004566 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4567 Cand2.Conversions[ArgIdx])) {
4568 case ImplicitConversionSequence::Better:
4569 // Cand1 has a better conversion sequence.
4570 HasBetterConversion = true;
4571 break;
4572
4573 case ImplicitConversionSequence::Worse:
4574 // Cand1 can't be better than Cand2.
4575 return false;
4576
4577 case ImplicitConversionSequence::Indistinguishable:
4578 // Do nothing.
4579 break;
4580 }
4581 }
4582
Mike Stump11289f42009-09-09 15:08:12 +00004583 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004584 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004585 if (HasBetterConversion)
4586 return true;
4587
Mike Stump11289f42009-09-09 15:08:12 +00004588 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004589 // specialization, or, if not that,
4590 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4591 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4592 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004593
4594 // -- F1 and F2 are function template specializations, and the function
4595 // template for F1 is more specialized than the template for F2
4596 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004597 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004598 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4599 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004600 if (FunctionTemplateDecl *BetterTemplate
4601 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4602 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004603 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004604 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4605 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004606 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004607
Douglas Gregora1f013e2008-11-07 22:36:19 +00004608 // -- the context is an initialization by user-defined conversion
4609 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4610 // from the return type of F1 to the destination type (i.e.,
4611 // the type of the entity being initialized) is a better
4612 // conversion sequence than the standard conversion sequence
4613 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004614 if (Cand1.Function && Cand2.Function &&
4615 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004616 isa<CXXConversionDecl>(Cand2.Function)) {
4617 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4618 Cand2.FinalConversion)) {
4619 case ImplicitConversionSequence::Better:
4620 // Cand1 has a better conversion sequence.
4621 return true;
4622
4623 case ImplicitConversionSequence::Worse:
4624 // Cand1 can't be better than Cand2.
4625 return false;
4626
4627 case ImplicitConversionSequence::Indistinguishable:
4628 // Do nothing
4629 break;
4630 }
4631 }
4632
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004633 return false;
4634}
4635
Mike Stump11289f42009-09-09 15:08:12 +00004636/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004637/// within an overload candidate set.
4638///
4639/// \param CandidateSet the set of candidate functions.
4640///
4641/// \param Loc the location of the function name (or operator symbol) for
4642/// which overload resolution occurs.
4643///
Mike Stump11289f42009-09-09 15:08:12 +00004644/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004645/// function, Best points to the candidate function found.
4646///
4647/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004648OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4649 SourceLocation Loc,
4650 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004651 // Find the best viable function.
4652 Best = CandidateSet.end();
4653 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4654 Cand != CandidateSet.end(); ++Cand) {
4655 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004656 if (Best == CandidateSet.end() ||
4657 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004658 Best = Cand;
4659 }
4660 }
4661
4662 // If we didn't find any viable functions, abort.
4663 if (Best == CandidateSet.end())
4664 return OR_No_Viable_Function;
4665
4666 // Make sure that this function is better than every other viable
4667 // function. If not, we have an ambiguity.
4668 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4669 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004670 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004671 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004672 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004673 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004674 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004675 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004676 }
Mike Stump11289f42009-09-09 15:08:12 +00004677
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004678 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004679 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004680 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004681 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004682 return OR_Deleted;
4683
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004684 // C++ [basic.def.odr]p2:
4685 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004686 // when referred to from a potentially-evaluated expression. [Note: this
4687 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004688 // (clause 13), user-defined conversions (12.3.2), allocation function for
4689 // placement new (5.3.4), as well as non-default initialization (8.5).
4690 if (Best->Function)
4691 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004692 return OR_Success;
4693}
4694
John McCall53262c92010-01-12 02:15:36 +00004695namespace {
4696
4697enum OverloadCandidateKind {
4698 oc_function,
4699 oc_method,
4700 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004701 oc_function_template,
4702 oc_method_template,
4703 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004704 oc_implicit_default_constructor,
4705 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004706 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004707};
4708
John McCalle1ac8d12010-01-13 00:25:19 +00004709OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4710 FunctionDecl *Fn,
4711 std::string &Description) {
4712 bool isTemplate = false;
4713
4714 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4715 isTemplate = true;
4716 Description = S.getTemplateArgumentBindingsText(
4717 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4718 }
John McCallfd0b2f82010-01-06 09:43:14 +00004719
4720 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004721 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004722 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004723
John McCall53262c92010-01-12 02:15:36 +00004724 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4725 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004726 }
4727
4728 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4729 // This actually gets spelled 'candidate function' for now, but
4730 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004731 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004732 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004733
4734 assert(Meth->isCopyAssignment()
4735 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004736 return oc_implicit_copy_assignment;
4737 }
4738
John McCalle1ac8d12010-01-13 00:25:19 +00004739 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004740}
4741
4742} // end anonymous namespace
4743
4744// Notes the location of an overload candidate.
4745void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004746 std::string FnDesc;
4747 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4748 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4749 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004750}
4751
John McCall0d1da222010-01-12 00:44:57 +00004752/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4753/// "lead" diagnostic; it will be given two arguments, the source and
4754/// target types of the conversion.
4755void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4756 SourceLocation CaretLoc,
4757 const PartialDiagnostic &PDiag) {
4758 Diag(CaretLoc, PDiag)
4759 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4760 for (AmbiguousConversionSequence::const_iterator
4761 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4762 NoteOverloadCandidate(*I);
4763 }
John McCall12f97bc2010-01-08 04:41:39 +00004764}
4765
John McCall0d1da222010-01-12 00:44:57 +00004766namespace {
4767
John McCall6a61b522010-01-13 09:16:55 +00004768void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4769 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4770 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004771 assert(Cand->Function && "for now, candidate must be a function");
4772 FunctionDecl *Fn = Cand->Function;
4773
4774 // There's a conversion slot for the object argument if this is a
4775 // non-constructor method. Note that 'I' corresponds the
4776 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004777 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004778 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004779 if (I == 0)
4780 isObjectArgument = true;
4781 else
4782 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004783 }
4784
John McCalle1ac8d12010-01-13 00:25:19 +00004785 std::string FnDesc;
4786 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4787
John McCall6a61b522010-01-13 09:16:55 +00004788 Expr *FromExpr = Conv.Bad.FromExpr;
4789 QualType FromTy = Conv.Bad.getFromType();
4790 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004791
John McCallfb7ad0f2010-02-02 02:42:52 +00004792 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004793 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004794 Expr *E = FromExpr->IgnoreParens();
4795 if (isa<UnaryOperator>(E))
4796 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004797 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004798
4799 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4800 << (unsigned) FnKind << FnDesc
4801 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4802 << ToTy << Name << I+1;
4803 return;
4804 }
4805
John McCall6d174642010-01-23 08:10:49 +00004806 // Do some hand-waving analysis to see if the non-viability is due
4807 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004808 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4809 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4810 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4811 CToTy = RT->getPointeeType();
4812 else {
4813 // TODO: detect and diagnose the full richness of const mismatches.
4814 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4815 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4816 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4817 }
4818
4819 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4820 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4821 // It is dumb that we have to do this here.
4822 while (isa<ArrayType>(CFromTy))
4823 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4824 while (isa<ArrayType>(CToTy))
4825 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4826
4827 Qualifiers FromQs = CFromTy.getQualifiers();
4828 Qualifiers ToQs = CToTy.getQualifiers();
4829
4830 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4831 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4832 << (unsigned) FnKind << FnDesc
4833 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4834 << FromTy
4835 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4836 << (unsigned) isObjectArgument << I+1;
4837 return;
4838 }
4839
4840 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4841 assert(CVR && "unexpected qualifiers mismatch");
4842
4843 if (isObjectArgument) {
4844 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4845 << (unsigned) FnKind << FnDesc
4846 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4847 << FromTy << (CVR - 1);
4848 } else {
4849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4850 << (unsigned) FnKind << FnDesc
4851 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4852 << FromTy << (CVR - 1) << I+1;
4853 }
4854 return;
4855 }
4856
John McCall6d174642010-01-23 08:10:49 +00004857 // Diagnose references or pointers to incomplete types differently,
4858 // since it's far from impossible that the incompleteness triggered
4859 // the failure.
4860 QualType TempFromTy = FromTy.getNonReferenceType();
4861 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4862 TempFromTy = PTy->getPointeeType();
4863 if (TempFromTy->isIncompleteType()) {
4864 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4865 << (unsigned) FnKind << FnDesc
4866 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4867 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4868 return;
4869 }
4870
John McCall47000992010-01-14 03:28:57 +00004871 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004872 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4873 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004874 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004875 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004876}
4877
4878void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4879 unsigned NumFormalArgs) {
4880 // TODO: treat calls to a missing default constructor as a special case
4881
4882 FunctionDecl *Fn = Cand->Function;
4883 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4884
4885 unsigned MinParams = Fn->getMinRequiredArguments();
4886
4887 // at least / at most / exactly
4888 unsigned mode, modeCount;
4889 if (NumFormalArgs < MinParams) {
4890 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4891 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4892 mode = 0; // "at least"
4893 else
4894 mode = 2; // "exactly"
4895 modeCount = MinParams;
4896 } else {
4897 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4898 if (MinParams != FnTy->getNumArgs())
4899 mode = 1; // "at most"
4900 else
4901 mode = 2; // "exactly"
4902 modeCount = FnTy->getNumArgs();
4903 }
4904
4905 std::string Description;
4906 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4907
4908 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4909 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004910}
4911
John McCall8b9ed552010-02-01 18:53:26 +00004912/// Diagnose a failed template-argument deduction.
4913void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4914 Expr **Args, unsigned NumArgs) {
4915 FunctionDecl *Fn = Cand->Function; // pattern
4916
4917 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4918 Cand->DeductionFailure.TemplateParameter);
4919
4920 switch (Cand->DeductionFailure.Result) {
4921 case Sema::TDK_Success:
4922 llvm_unreachable("TDK_success while diagnosing bad deduction");
4923
4924 case Sema::TDK_Incomplete: {
4925 NamedDecl *ParamD;
4926 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4927 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4928 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4929 assert(ParamD && "no parameter found for incomplete deduction result");
4930 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4931 << ParamD->getDeclName();
4932 return;
4933 }
4934
4935 // TODO: diagnose these individually, then kill off
4936 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4937 case Sema::TDK_InstantiationDepth:
4938 case Sema::TDK_Inconsistent:
4939 case Sema::TDK_InconsistentQuals:
4940 case Sema::TDK_SubstitutionFailure:
4941 case Sema::TDK_NonDeducedMismatch:
4942 case Sema::TDK_TooManyArguments:
4943 case Sema::TDK_TooFewArguments:
4944 case Sema::TDK_InvalidExplicitArguments:
4945 case Sema::TDK_FailedOverloadResolution:
4946 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4947 return;
4948 }
4949}
4950
4951/// Generates a 'note' diagnostic for an overload candidate. We've
4952/// already generated a primary error at the call site.
4953///
4954/// It really does need to be a single diagnostic with its caret
4955/// pointed at the candidate declaration. Yes, this creates some
4956/// major challenges of technical writing. Yes, this makes pointing
4957/// out problems with specific arguments quite awkward. It's still
4958/// better than generating twenty screens of text for every failed
4959/// overload.
4960///
4961/// It would be great to be able to express per-candidate problems
4962/// more richly for those diagnostic clients that cared, but we'd
4963/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004964void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4965 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004966 FunctionDecl *Fn = Cand->Function;
4967
John McCall12f97bc2010-01-08 04:41:39 +00004968 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004969 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004970 std::string FnDesc;
4971 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004972
4973 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004974 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004975 return;
John McCall12f97bc2010-01-08 04:41:39 +00004976 }
4977
John McCalle1ac8d12010-01-13 00:25:19 +00004978 // We don't really have anything else to say about viable candidates.
4979 if (Cand->Viable) {
4980 S.NoteOverloadCandidate(Fn);
4981 return;
4982 }
John McCall0d1da222010-01-12 00:44:57 +00004983
John McCall6a61b522010-01-13 09:16:55 +00004984 switch (Cand->FailureKind) {
4985 case ovl_fail_too_many_arguments:
4986 case ovl_fail_too_few_arguments:
4987 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004988
John McCall6a61b522010-01-13 09:16:55 +00004989 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004990 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4991
John McCallfe796dd2010-01-23 05:17:32 +00004992 case ovl_fail_trivial_conversion:
4993 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004994 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00004995 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004996
John McCall65eb8792010-02-25 01:37:24 +00004997 case ovl_fail_bad_conversion: {
4998 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4999 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005000 if (Cand->Conversions[I].isBad())
5001 return DiagnoseBadConversion(S, Cand, I);
5002
5003 // FIXME: this currently happens when we're called from SemaInit
5004 // when user-conversion overload fails. Figure out how to handle
5005 // those conditions and diagnose them well.
5006 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005007 }
John McCall65eb8792010-02-25 01:37:24 +00005008 }
John McCalld3224162010-01-08 00:58:21 +00005009}
5010
5011void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5012 // Desugar the type of the surrogate down to a function type,
5013 // retaining as many typedefs as possible while still showing
5014 // the function type (and, therefore, its parameter types).
5015 QualType FnType = Cand->Surrogate->getConversionType();
5016 bool isLValueReference = false;
5017 bool isRValueReference = false;
5018 bool isPointer = false;
5019 if (const LValueReferenceType *FnTypeRef =
5020 FnType->getAs<LValueReferenceType>()) {
5021 FnType = FnTypeRef->getPointeeType();
5022 isLValueReference = true;
5023 } else if (const RValueReferenceType *FnTypeRef =
5024 FnType->getAs<RValueReferenceType>()) {
5025 FnType = FnTypeRef->getPointeeType();
5026 isRValueReference = true;
5027 }
5028 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5029 FnType = FnTypePtr->getPointeeType();
5030 isPointer = true;
5031 }
5032 // Desugar down to a function type.
5033 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5034 // Reconstruct the pointer/reference as appropriate.
5035 if (isPointer) FnType = S.Context.getPointerType(FnType);
5036 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5037 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5038
5039 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5040 << FnType;
5041}
5042
5043void NoteBuiltinOperatorCandidate(Sema &S,
5044 const char *Opc,
5045 SourceLocation OpLoc,
5046 OverloadCandidate *Cand) {
5047 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5048 std::string TypeStr("operator");
5049 TypeStr += Opc;
5050 TypeStr += "(";
5051 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5052 if (Cand->Conversions.size() == 1) {
5053 TypeStr += ")";
5054 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5055 } else {
5056 TypeStr += ", ";
5057 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5058 TypeStr += ")";
5059 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5060 }
5061}
5062
5063void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5064 OverloadCandidate *Cand) {
5065 unsigned NoOperands = Cand->Conversions.size();
5066 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5067 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005068 if (ICS.isBad()) break; // all meaningless after first invalid
5069 if (!ICS.isAmbiguous()) continue;
5070
5071 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005072 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005073 }
5074}
5075
John McCall3712d9e2010-01-15 23:32:50 +00005076SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5077 if (Cand->Function)
5078 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005079 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005080 return Cand->Surrogate->getLocation();
5081 return SourceLocation();
5082}
5083
John McCallad2587a2010-01-12 00:48:53 +00005084struct CompareOverloadCandidatesForDisplay {
5085 Sema &S;
5086 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005087
5088 bool operator()(const OverloadCandidate *L,
5089 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005090 // Fast-path this check.
5091 if (L == R) return false;
5092
John McCall12f97bc2010-01-08 04:41:39 +00005093 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005094 if (L->Viable) {
5095 if (!R->Viable) return true;
5096
5097 // TODO: introduce a tri-valued comparison for overload
5098 // candidates. Would be more worthwhile if we had a sort
5099 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005100 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5101 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005102 } else if (R->Viable)
5103 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005104
John McCall3712d9e2010-01-15 23:32:50 +00005105 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005106
John McCall3712d9e2010-01-15 23:32:50 +00005107 // Criteria by which we can sort non-viable candidates:
5108 if (!L->Viable) {
5109 // 1. Arity mismatches come after other candidates.
5110 if (L->FailureKind == ovl_fail_too_many_arguments ||
5111 L->FailureKind == ovl_fail_too_few_arguments)
5112 return false;
5113 if (R->FailureKind == ovl_fail_too_many_arguments ||
5114 R->FailureKind == ovl_fail_too_few_arguments)
5115 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005116
John McCallfe796dd2010-01-23 05:17:32 +00005117 // 2. Bad conversions come first and are ordered by the number
5118 // of bad conversions and quality of good conversions.
5119 if (L->FailureKind == ovl_fail_bad_conversion) {
5120 if (R->FailureKind != ovl_fail_bad_conversion)
5121 return true;
5122
5123 // If there's any ordering between the defined conversions...
5124 // FIXME: this might not be transitive.
5125 assert(L->Conversions.size() == R->Conversions.size());
5126
5127 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005128 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5129 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005130 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5131 R->Conversions[I])) {
5132 case ImplicitConversionSequence::Better:
5133 leftBetter++;
5134 break;
5135
5136 case ImplicitConversionSequence::Worse:
5137 leftBetter--;
5138 break;
5139
5140 case ImplicitConversionSequence::Indistinguishable:
5141 break;
5142 }
5143 }
5144 if (leftBetter > 0) return true;
5145 if (leftBetter < 0) return false;
5146
5147 } else if (R->FailureKind == ovl_fail_bad_conversion)
5148 return false;
5149
John McCall3712d9e2010-01-15 23:32:50 +00005150 // TODO: others?
5151 }
5152
5153 // Sort everything else by location.
5154 SourceLocation LLoc = GetLocationForCandidate(L);
5155 SourceLocation RLoc = GetLocationForCandidate(R);
5156
5157 // Put candidates without locations (e.g. builtins) at the end.
5158 if (LLoc.isInvalid()) return false;
5159 if (RLoc.isInvalid()) return true;
5160
5161 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005162 }
5163};
5164
John McCallfe796dd2010-01-23 05:17:32 +00005165/// CompleteNonViableCandidate - Normally, overload resolution only
5166/// computes up to the first
5167void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5168 Expr **Args, unsigned NumArgs) {
5169 assert(!Cand->Viable);
5170
5171 // Don't do anything on failures other than bad conversion.
5172 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5173
5174 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005175 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005176 unsigned ConvCount = Cand->Conversions.size();
5177 while (true) {
5178 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5179 ConvIdx++;
5180 if (Cand->Conversions[ConvIdx - 1].isBad())
5181 break;
5182 }
5183
5184 if (ConvIdx == ConvCount)
5185 return;
5186
John McCall65eb8792010-02-25 01:37:24 +00005187 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5188 "remaining conversion is initialized?");
5189
Douglas Gregoradc7a702010-04-16 17:45:54 +00005190 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005191 // operation somehow.
5192 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005193
5194 const FunctionProtoType* Proto;
5195 unsigned ArgIdx = ConvIdx;
5196
5197 if (Cand->IsSurrogate) {
5198 QualType ConvType
5199 = Cand->Surrogate->getConversionType().getNonReferenceType();
5200 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5201 ConvType = ConvPtrType->getPointeeType();
5202 Proto = ConvType->getAs<FunctionProtoType>();
5203 ArgIdx--;
5204 } else if (Cand->Function) {
5205 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5206 if (isa<CXXMethodDecl>(Cand->Function) &&
5207 !isa<CXXConstructorDecl>(Cand->Function))
5208 ArgIdx--;
5209 } else {
5210 // Builtin binary operator with a bad first conversion.
5211 assert(ConvCount <= 3);
5212 for (; ConvIdx != ConvCount; ++ConvIdx)
5213 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005214 = TryCopyInitialization(S, Args[ConvIdx],
5215 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5216 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005217 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005218 return;
5219 }
5220
5221 // Fill in the rest of the conversions.
5222 unsigned NumArgsInProto = Proto->getNumArgs();
5223 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5224 if (ArgIdx < NumArgsInProto)
5225 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005226 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5227 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005228 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005229 else
5230 Cand->Conversions[ConvIdx].setEllipsis();
5231 }
5232}
5233
John McCalld3224162010-01-08 00:58:21 +00005234} // end anonymous namespace
5235
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005236/// PrintOverloadCandidates - When overload resolution fails, prints
5237/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005238/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005239void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005240Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005241 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005242 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005243 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005244 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005245 // Sort the candidates by viability and position. Sorting directly would
5246 // be prohibitive, so we make a set of pointers and sort those.
5247 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5248 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5249 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5250 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005251 Cand != LastCand; ++Cand) {
5252 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005253 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005254 else if (OCD == OCD_AllCandidates) {
5255 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5256 Cands.push_back(Cand);
5257 }
5258 }
5259
John McCallad2587a2010-01-12 00:48:53 +00005260 std::sort(Cands.begin(), Cands.end(),
5261 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005262
John McCall0d1da222010-01-12 00:44:57 +00005263 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005264
John McCall12f97bc2010-01-08 04:41:39 +00005265 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5266 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5267 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005268
John McCalld3224162010-01-08 00:58:21 +00005269 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005270 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005271 else if (Cand->IsSurrogate)
5272 NoteSurrogateCandidate(*this, Cand);
5273
5274 // This a builtin candidate. We do not, in general, want to list
5275 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005276 else if (Cand->Viable) {
5277 // Generally we only see ambiguities including viable builtin
5278 // operators if overload resolution got screwed up by an
5279 // ambiguous user-defined conversion.
5280 //
5281 // FIXME: It's quite possible for different conversions to see
5282 // different ambiguities, though.
5283 if (!ReportedAmbiguousConversions) {
5284 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5285 ReportedAmbiguousConversions = true;
5286 }
John McCalld3224162010-01-08 00:58:21 +00005287
John McCall0d1da222010-01-12 00:44:57 +00005288 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005289 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005290 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005291 }
5292}
5293
John McCalla0296f72010-03-19 07:35:19 +00005294static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005295 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005296 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005297
John McCalla0296f72010-03-19 07:35:19 +00005298 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005299}
5300
Douglas Gregorcd695e52008-11-10 20:40:00 +00005301/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5302/// an overloaded function (C++ [over.over]), where @p From is an
5303/// expression with overloaded function type and @p ToType is the type
5304/// we're trying to resolve to. For example:
5305///
5306/// @code
5307/// int f(double);
5308/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005309///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005310/// int (*pfd)(double) = f; // selects f(double)
5311/// @endcode
5312///
5313/// This routine returns the resulting FunctionDecl if it could be
5314/// resolved, and NULL otherwise. When @p Complain is true, this
5315/// routine will emit diagnostics if there is an error.
5316FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005317Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005318 bool Complain,
5319 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005320 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005321 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005322 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005323 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005324 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005325 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005326 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005327 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005328 FunctionType = MemTypePtr->getPointeeType();
5329 IsMember = true;
5330 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005331
Douglas Gregorcd695e52008-11-10 20:40:00 +00005332 // C++ [over.over]p1:
5333 // [...] [Note: any redundant set of parentheses surrounding the
5334 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005335 // C++ [over.over]p1:
5336 // [...] The overloaded function name can be preceded by the &
5337 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005338 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5339 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5340 if (OvlExpr->hasExplicitTemplateArgs()) {
5341 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5342 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005343 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005344
5345 // We expect a pointer or reference to function, or a function pointer.
5346 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5347 if (!FunctionType->isFunctionType()) {
5348 if (Complain)
5349 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5350 << OvlExpr->getName() << ToType;
5351
5352 return 0;
5353 }
5354
5355 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005356
Douglas Gregorcd695e52008-11-10 20:40:00 +00005357 // Look through all of the overloaded functions, searching for one
5358 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005359 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005360 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5361
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005362 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005363 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5364 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005365 // Look through any using declarations to find the underlying function.
5366 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5367
Douglas Gregorcd695e52008-11-10 20:40:00 +00005368 // C++ [over.over]p3:
5369 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005370 // targets of type "pointer-to-function" or "reference-to-function."
5371 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005372 // type "pointer-to-member-function."
5373 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005374
Mike Stump11289f42009-09-09 15:08:12 +00005375 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005376 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005377 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005378 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005379 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005380 // static when converting to member pointer.
5381 if (Method->isStatic() == IsMember)
5382 continue;
5383 } else if (IsMember)
5384 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005385
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005386 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005387 // If the name is a function template, template argument deduction is
5388 // done (14.8.2.2), and if the argument deduction succeeds, the
5389 // resulting template argument list is used to generate a single
5390 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005391 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005392 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005393 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005394 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005395 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005396 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005397 FunctionType, Specialization, Info)) {
5398 // FIXME: make a note of the failed deduction for diagnostics.
5399 (void)Result;
5400 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005401 // FIXME: If the match isn't exact, shouldn't we just drop this as
5402 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005403 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005404 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005405 Matches.push_back(std::make_pair(I.getPair(),
5406 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005407 }
John McCalld14a8642009-11-21 08:51:07 +00005408
5409 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005410 }
Mike Stump11289f42009-09-09 15:08:12 +00005411
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005412 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005413 // Skip non-static functions when converting to pointer, and static
5414 // when converting to member pointer.
5415 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005416 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005417
5418 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005419 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005420 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005421 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005422 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005423
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005424 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005425 QualType ResultTy;
5426 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5427 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5428 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005429 Matches.push_back(std::make_pair(I.getPair(),
5430 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005431 FoundNonTemplateFunction = true;
5432 }
Mike Stump11289f42009-09-09 15:08:12 +00005433 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005434 }
5435
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005436 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005437 if (Matches.empty()) {
5438 if (Complain) {
5439 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5440 << OvlExpr->getName() << FunctionType;
5441 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5442 E = OvlExpr->decls_end();
5443 I != E; ++I)
5444 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5445 NoteOverloadCandidate(F);
5446 }
5447
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005448 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005449 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005450 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005451 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005452 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005453 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005454 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005455 return Result;
5456 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005457
5458 // C++ [over.over]p4:
5459 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005460 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005461 // [...] and any given function template specialization F1 is
5462 // eliminated if the set contains a second function template
5463 // specialization whose function template is more specialized
5464 // than the function template of F1 according to the partial
5465 // ordering rules of 14.5.5.2.
5466
5467 // The algorithm specified above is quadratic. We instead use a
5468 // two-pass algorithm (similar to the one used to identify the
5469 // best viable function in an overload set) that identifies the
5470 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005471
5472 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5473 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5474 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005475
5476 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005477 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005478 TPOC_Other, From->getLocStart(),
5479 PDiag(),
5480 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005481 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005482 PDiag(diag::note_ovl_candidate)
5483 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005484 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005485 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005486 FoundResult = Matches[Result - MatchesCopy.begin()].first;
5487 if (Complain)
5488 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00005489 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005490 }
Mike Stump11289f42009-09-09 15:08:12 +00005491
Douglas Gregorfae1d712009-09-26 03:56:17 +00005492 // [...] any function template specializations in the set are
5493 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005494 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005495 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005496 ++I;
5497 else {
John McCalla0296f72010-03-19 07:35:19 +00005498 Matches[I] = Matches[--N];
5499 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005500 }
5501 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005502
Mike Stump11289f42009-09-09 15:08:12 +00005503 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005504 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005505 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005506 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005507 FoundResult = Matches[0].first;
John McCall58cc69d2010-01-27 01:50:18 +00005508 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00005509 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5510 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005511 }
Mike Stump11289f42009-09-09 15:08:12 +00005512
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005513 // FIXME: We should probably return the same thing that BestViableFunction
5514 // returns (even if we issue the diagnostics here).
5515 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005516 << Matches[0].second->getDeclName();
5517 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5518 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005519 return 0;
5520}
5521
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005522/// \brief Given an expression that refers to an overloaded function, try to
5523/// resolve that overloaded function expression down to a single function.
5524///
5525/// This routine can only resolve template-ids that refer to a single function
5526/// template, where that template-id refers to a single template whose template
5527/// arguments are either provided by the template-id or have defaults,
5528/// as described in C++0x [temp.arg.explicit]p3.
5529FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5530 // C++ [over.over]p1:
5531 // [...] [Note: any redundant set of parentheses surrounding the
5532 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005533 // C++ [over.over]p1:
5534 // [...] The overloaded function name can be preceded by the &
5535 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005536
5537 if (From->getType() != Context.OverloadTy)
5538 return 0;
5539
5540 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005541
5542 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005543 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005544 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005545
5546 TemplateArgumentListInfo ExplicitTemplateArgs;
5547 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005548
5549 // Look through all of the overloaded functions, searching for one
5550 // whose type matches exactly.
5551 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005552 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5553 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005554 // C++0x [temp.arg.explicit]p3:
5555 // [...] In contexts where deduction is done and fails, or in contexts
5556 // where deduction is not done, if a template argument list is
5557 // specified and it, along with any default template arguments,
5558 // identifies a single function template specialization, then the
5559 // template-id is an lvalue for the function template specialization.
5560 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5561
5562 // C++ [over.over]p2:
5563 // If the name is a function template, template argument deduction is
5564 // done (14.8.2.2), and if the argument deduction succeeds, the
5565 // resulting template argument list is used to generate a single
5566 // function template specialization, which is added to the set of
5567 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005568 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005569 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005570 if (TemplateDeductionResult Result
5571 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5572 Specialization, Info)) {
5573 // FIXME: make a note of the failed deduction for diagnostics.
5574 (void)Result;
5575 continue;
5576 }
5577
5578 // Multiple matches; we can't resolve to a single declaration.
5579 if (Matched)
5580 return 0;
5581
5582 Matched = Specialization;
5583 }
5584
5585 return Matched;
5586}
5587
Douglas Gregorcabea402009-09-22 15:41:20 +00005588/// \brief Add a single candidate to the overload set.
5589static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005590 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005591 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005592 Expr **Args, unsigned NumArgs,
5593 OverloadCandidateSet &CandidateSet,
5594 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005595 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005596 if (isa<UsingShadowDecl>(Callee))
5597 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5598
Douglas Gregorcabea402009-09-22 15:41:20 +00005599 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005600 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005601 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005602 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005603 return;
John McCalld14a8642009-11-21 08:51:07 +00005604 }
5605
5606 if (FunctionTemplateDecl *FuncTemplate
5607 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005608 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5609 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005610 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005611 return;
5612 }
5613
5614 assert(false && "unhandled case in overloaded call candidate");
5615
5616 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005617}
5618
5619/// \brief Add the overload candidates named by callee and/or found by argument
5620/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005621void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005622 Expr **Args, unsigned NumArgs,
5623 OverloadCandidateSet &CandidateSet,
5624 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005625
5626#ifndef NDEBUG
5627 // Verify that ArgumentDependentLookup is consistent with the rules
5628 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005629 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005630 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5631 // and let Y be the lookup set produced by argument dependent
5632 // lookup (defined as follows). If X contains
5633 //
5634 // -- a declaration of a class member, or
5635 //
5636 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005637 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005638 //
5639 // -- a declaration that is neither a function or a function
5640 // template
5641 //
5642 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005643
John McCall57500772009-12-16 12:17:52 +00005644 if (ULE->requiresADL()) {
5645 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5646 E = ULE->decls_end(); I != E; ++I) {
5647 assert(!(*I)->getDeclContext()->isRecord());
5648 assert(isa<UsingShadowDecl>(*I) ||
5649 !(*I)->getDeclContext()->isFunctionOrMethod());
5650 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005651 }
5652 }
5653#endif
5654
John McCall57500772009-12-16 12:17:52 +00005655 // It would be nice to avoid this copy.
5656 TemplateArgumentListInfo TABuffer;
5657 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5658 if (ULE->hasExplicitTemplateArgs()) {
5659 ULE->copyTemplateArgumentsInto(TABuffer);
5660 ExplicitTemplateArgs = &TABuffer;
5661 }
5662
5663 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5664 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005665 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005666 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005667 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005668
John McCall57500772009-12-16 12:17:52 +00005669 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005670 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5671 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005672 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005673 CandidateSet,
5674 PartialOverloading);
5675}
John McCalld681c392009-12-16 08:11:27 +00005676
John McCall57500772009-12-16 12:17:52 +00005677static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5678 Expr **Args, unsigned NumArgs) {
5679 Fn->Destroy(SemaRef.Context);
5680 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5681 Args[Arg]->Destroy(SemaRef.Context);
5682 return SemaRef.ExprError();
5683}
5684
John McCalld681c392009-12-16 08:11:27 +00005685/// Attempts to recover from a call where no functions were found.
5686///
5687/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005688static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005689BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005690 UnresolvedLookupExpr *ULE,
5691 SourceLocation LParenLoc,
5692 Expr **Args, unsigned NumArgs,
5693 SourceLocation *CommaLocs,
5694 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005695
5696 CXXScopeSpec SS;
5697 if (ULE->getQualifier()) {
5698 SS.setScopeRep(ULE->getQualifier());
5699 SS.setRange(ULE->getQualifierRange());
5700 }
5701
John McCall57500772009-12-16 12:17:52 +00005702 TemplateArgumentListInfo TABuffer;
5703 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5704 if (ULE->hasExplicitTemplateArgs()) {
5705 ULE->copyTemplateArgumentsInto(TABuffer);
5706 ExplicitTemplateArgs = &TABuffer;
5707 }
5708
John McCalld681c392009-12-16 08:11:27 +00005709 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5710 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005711 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005712 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005713
John McCall57500772009-12-16 12:17:52 +00005714 assert(!R.empty() && "lookup results empty despite recovery");
5715
5716 // Build an implicit member call if appropriate. Just drop the
5717 // casts and such from the call, we don't really care.
5718 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5719 if ((*R.begin())->isCXXClassMember())
5720 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5721 else if (ExplicitTemplateArgs)
5722 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5723 else
5724 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5725
5726 if (NewFn.isInvalid())
5727 return Destroy(SemaRef, Fn, Args, NumArgs);
5728
5729 Fn->Destroy(SemaRef.Context);
5730
5731 // This shouldn't cause an infinite loop because we're giving it
5732 // an expression with non-empty lookup results, which should never
5733 // end up here.
5734 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5735 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5736 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005737}
Douglas Gregorcabea402009-09-22 15:41:20 +00005738
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005739/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005740/// (which eventually refers to the declaration Func) and the call
5741/// arguments Args/NumArgs, attempt to resolve the function call down
5742/// to a specific function. If overload resolution succeeds, returns
5743/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005744/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005745/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005746Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005747Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005748 SourceLocation LParenLoc,
5749 Expr **Args, unsigned NumArgs,
5750 SourceLocation *CommaLocs,
5751 SourceLocation RParenLoc) {
5752#ifndef NDEBUG
5753 if (ULE->requiresADL()) {
5754 // To do ADL, we must have found an unqualified name.
5755 assert(!ULE->getQualifier() && "qualified name with ADL");
5756
5757 // We don't perform ADL for implicit declarations of builtins.
5758 // Verify that this was correctly set up.
5759 FunctionDecl *F;
5760 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5761 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5762 F->getBuiltinID() && F->isImplicit())
5763 assert(0 && "performing ADL for builtin");
5764
5765 // We don't perform ADL in C.
5766 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5767 }
5768#endif
5769
John McCallbc077cf2010-02-08 23:07:23 +00005770 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005771
John McCall57500772009-12-16 12:17:52 +00005772 // Add the functions denoted by the callee to the set of candidate
5773 // functions, including those from argument-dependent lookup.
5774 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005775
5776 // If we found nothing, try to recover.
5777 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5778 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005779 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005780 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00005781 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005782
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005783 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005784 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005785 case OR_Success: {
5786 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00005787 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall16df1e52010-03-30 21:47:33 +00005788 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00005789 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5790 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005791
5792 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005793 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005794 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005795 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005796 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005797 break;
5798
5799 case OR_Ambiguous:
5800 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005801 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005802 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005803 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005804
5805 case OR_Deleted:
5806 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5807 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005808 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005809 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005810 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005811 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005812 }
5813
5814 // Overload resolution failed. Destroy all of the subexpressions and
5815 // return NULL.
5816 Fn->Destroy(Context);
5817 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5818 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005819 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005820}
5821
John McCall4c4c1df2010-01-26 03:27:55 +00005822static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005823 return Functions.size() > 1 ||
5824 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5825}
5826
Douglas Gregor084d8552009-03-13 23:49:33 +00005827/// \brief Create a unary operation that may resolve to an overloaded
5828/// operator.
5829///
5830/// \param OpLoc The location of the operator itself (e.g., '*').
5831///
5832/// \param OpcIn The UnaryOperator::Opcode that describes this
5833/// operator.
5834///
5835/// \param Functions The set of non-member functions that will be
5836/// considered by overload resolution. The caller needs to build this
5837/// set based on the context using, e.g.,
5838/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5839/// set should not contain any member functions; those will be added
5840/// by CreateOverloadedUnaryOp().
5841///
5842/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005843Sema::OwningExprResult
5844Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5845 const UnresolvedSetImpl &Fns,
5846 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005847 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5848 Expr *Input = (Expr *)input.get();
5849
5850 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5851 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5852 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5853
5854 Expr *Args[2] = { Input, 0 };
5855 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005856
Douglas Gregor084d8552009-03-13 23:49:33 +00005857 // For post-increment and post-decrement, add the implicit '0' as
5858 // the second argument, so that we know this is a post-increment or
5859 // post-decrement.
5860 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5861 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005862 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005863 SourceLocation());
5864 NumArgs = 2;
5865 }
5866
5867 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005868 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005869 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005870 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005871 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005872 /*ADL*/ true, IsOverloaded(Fns));
5873 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005874
Douglas Gregor084d8552009-03-13 23:49:33 +00005875 input.release();
5876 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5877 &Args[0], NumArgs,
5878 Context.DependentTy,
5879 OpLoc));
5880 }
5881
5882 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005883 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005884
5885 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005886 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005887
5888 // Add operator candidates that are member functions.
5889 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5890
John McCall4c4c1df2010-01-26 03:27:55 +00005891 // Add candidates from ADL.
5892 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005893 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005894 /*ExplicitTemplateArgs*/ 0,
5895 CandidateSet);
5896
Douglas Gregor084d8552009-03-13 23:49:33 +00005897 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005898 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005899
5900 // Perform overload resolution.
5901 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005902 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005903 case OR_Success: {
5904 // We found a built-in operator or an overloaded operator.
5905 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005906
Douglas Gregor084d8552009-03-13 23:49:33 +00005907 if (FnDecl) {
5908 // We matched an overloaded operator. Build a call to that
5909 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005910
Douglas Gregor084d8552009-03-13 23:49:33 +00005911 // Convert the arguments.
5912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00005913 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00005914
John McCall16df1e52010-03-30 21:47:33 +00005915 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5916 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005917 return ExprError();
5918 } else {
5919 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005920 OwningExprResult InputInit
5921 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005922 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005923 SourceLocation(),
5924 move(input));
5925 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005926 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005927
Douglas Gregore6600372009-12-23 17:40:29 +00005928 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005929 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005930 }
5931
5932 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005933 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005934
Douglas Gregor084d8552009-03-13 23:49:33 +00005935 // Build the actual expression node.
5936 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5937 SourceLocation());
5938 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005939
Douglas Gregor084d8552009-03-13 23:49:33 +00005940 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005941 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005942 ExprOwningPtr<CallExpr> TheCall(this,
5943 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005944 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005945
5946 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5947 FnDecl))
5948 return ExprError();
5949
5950 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005951 } else {
5952 // We matched a built-in operator. Convert the arguments, then
5953 // break out so that we will build the appropriate built-in
5954 // operator node.
5955 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005956 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005957 return ExprError();
5958
5959 break;
5960 }
5961 }
5962
5963 case OR_No_Viable_Function:
5964 // No viable function; fall through to handling this as a
5965 // built-in operator, which will produce an error message for us.
5966 break;
5967
5968 case OR_Ambiguous:
5969 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5970 << UnaryOperator::getOpcodeStr(Opc)
5971 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005972 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005973 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005974 return ExprError();
5975
5976 case OR_Deleted:
5977 Diag(OpLoc, diag::err_ovl_deleted_oper)
5978 << Best->Function->isDeleted()
5979 << UnaryOperator::getOpcodeStr(Opc)
5980 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005981 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005982 return ExprError();
5983 }
5984
5985 // Either we found no viable overloaded operator or we matched a
5986 // built-in operator. In either case, fall through to trying to
5987 // build a built-in operation.
5988 input.release();
5989 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5990}
5991
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005992/// \brief Create a binary operation that may resolve to an overloaded
5993/// operator.
5994///
5995/// \param OpLoc The location of the operator itself (e.g., '+').
5996///
5997/// \param OpcIn The BinaryOperator::Opcode that describes this
5998/// operator.
5999///
6000/// \param Functions The set of non-member functions that will be
6001/// considered by overload resolution. The caller needs to build this
6002/// set based on the context using, e.g.,
6003/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6004/// set should not contain any member functions; those will be added
6005/// by CreateOverloadedBinOp().
6006///
6007/// \param LHS Left-hand argument.
6008/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006009Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006010Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006011 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006012 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006013 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006014 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006015 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006016
6017 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6018 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6019 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6020
6021 // If either side is type-dependent, create an appropriate dependent
6022 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006023 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006024 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006025 // If there are no functions to store, just build a dependent
6026 // BinaryOperator or CompoundAssignment.
6027 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6028 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6029 Context.DependentTy, OpLoc));
6030
6031 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6032 Context.DependentTy,
6033 Context.DependentTy,
6034 Context.DependentTy,
6035 OpLoc));
6036 }
John McCall4c4c1df2010-01-26 03:27:55 +00006037
6038 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006039 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006040 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006041 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006042 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006043 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006044
John McCall4c4c1df2010-01-26 03:27:55 +00006045 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006046 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006047 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006048 Context.DependentTy,
6049 OpLoc));
6050 }
6051
6052 // If this is the .* operator, which is not overloadable, just
6053 // create a built-in binary operator.
6054 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006055 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006056
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006057 // If this is the assignment operator, we only perform overload resolution
6058 // if the left-hand side is a class or enumeration type. This is actually
6059 // a hack. The standard requires that we do overload resolution between the
6060 // various built-in candidates, but as DR507 points out, this can lead to
6061 // problems. So we do it this way, which pretty much follows what GCC does.
6062 // Note that we go the traditional code path for compound assignment forms.
6063 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006064 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006065
Douglas Gregor084d8552009-03-13 23:49:33 +00006066 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006067 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006068
6069 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006070 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006071
6072 // Add operator candidates that are member functions.
6073 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6074
John McCall4c4c1df2010-01-26 03:27:55 +00006075 // Add candidates from ADL.
6076 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6077 Args, 2,
6078 /*ExplicitTemplateArgs*/ 0,
6079 CandidateSet);
6080
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006081 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006082 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006083
6084 // Perform overload resolution.
6085 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006086 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006087 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006088 // We found a built-in operator or an overloaded operator.
6089 FunctionDecl *FnDecl = Best->Function;
6090
6091 if (FnDecl) {
6092 // We matched an overloaded operator. Build a call to that
6093 // operator.
6094
6095 // Convert the arguments.
6096 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006097 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006098 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006099
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006100 OwningExprResult Arg1
6101 = PerformCopyInitialization(
6102 InitializedEntity::InitializeParameter(
6103 FnDecl->getParamDecl(0)),
6104 SourceLocation(),
6105 Owned(Args[1]));
6106 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006107 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006108
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006109 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006110 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006111 return ExprError();
6112
6113 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006114 } else {
6115 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006116 OwningExprResult Arg0
6117 = PerformCopyInitialization(
6118 InitializedEntity::InitializeParameter(
6119 FnDecl->getParamDecl(0)),
6120 SourceLocation(),
6121 Owned(Args[0]));
6122 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006123 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006124
6125 OwningExprResult Arg1
6126 = PerformCopyInitialization(
6127 InitializedEntity::InitializeParameter(
6128 FnDecl->getParamDecl(1)),
6129 SourceLocation(),
6130 Owned(Args[1]));
6131 if (Arg1.isInvalid())
6132 return ExprError();
6133 Args[0] = LHS = Arg0.takeAs<Expr>();
6134 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006135 }
6136
6137 // Determine the result type
6138 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006139 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006140 ResultTy = ResultTy.getNonReferenceType();
6141
6142 // Build the actual expression node.
6143 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006144 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006145 UsualUnaryConversions(FnExpr);
6146
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006147 ExprOwningPtr<CXXOperatorCallExpr>
6148 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6149 Args, 2, ResultTy,
6150 OpLoc));
6151
6152 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6153 FnDecl))
6154 return ExprError();
6155
6156 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006157 } else {
6158 // We matched a built-in operator. Convert the arguments, then
6159 // break out so that we will build the appropriate built-in
6160 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006161 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006162 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006163 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006164 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006165 return ExprError();
6166
6167 break;
6168 }
6169 }
6170
Douglas Gregor66950a32009-09-30 21:46:01 +00006171 case OR_No_Viable_Function: {
6172 // C++ [over.match.oper]p9:
6173 // If the operator is the operator , [...] and there are no
6174 // viable functions, then the operator is assumed to be the
6175 // built-in operator and interpreted according to clause 5.
6176 if (Opc == BinaryOperator::Comma)
6177 break;
6178
Sebastian Redl027de2a2009-05-21 11:50:50 +00006179 // For class as left operand for assignment or compound assigment operator
6180 // do not fall through to handling in built-in, but report that no overloaded
6181 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006182 OwningExprResult Result = ExprError();
6183 if (Args[0]->getType()->isRecordType() &&
6184 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006185 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6186 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006187 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006188 } else {
6189 // No viable function; try to create a built-in operation, which will
6190 // produce an error. Then, show the non-viable candidates.
6191 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006192 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006193 assert(Result.isInvalid() &&
6194 "C++ binary operator overloading is missing candidates!");
6195 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006196 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006197 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006198 return move(Result);
6199 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006200
6201 case OR_Ambiguous:
6202 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6203 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006204 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006205 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006206 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006207 return ExprError();
6208
6209 case OR_Deleted:
6210 Diag(OpLoc, diag::err_ovl_deleted_oper)
6211 << Best->Function->isDeleted()
6212 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006213 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006214 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006215 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006216 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006217
Douglas Gregor66950a32009-09-30 21:46:01 +00006218 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006219 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006220}
6221
Sebastian Redladba46e2009-10-29 20:17:01 +00006222Action::OwningExprResult
6223Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6224 SourceLocation RLoc,
6225 ExprArg Base, ExprArg Idx) {
6226 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6227 static_cast<Expr*>(Idx.get()) };
6228 DeclarationName OpName =
6229 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6230
6231 // If either side is type-dependent, create an appropriate dependent
6232 // expression.
6233 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6234
John McCall58cc69d2010-01-27 01:50:18 +00006235 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006236 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006237 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006238 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006239 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006240 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006241
6242 Base.release();
6243 Idx.release();
6244 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6245 Args, 2,
6246 Context.DependentTy,
6247 RLoc));
6248 }
6249
6250 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006251 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006252
6253 // Subscript can only be overloaded as a member function.
6254
6255 // Add operator candidates that are member functions.
6256 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6257
6258 // Add builtin operator candidates.
6259 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6260
6261 // Perform overload resolution.
6262 OverloadCandidateSet::iterator Best;
6263 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6264 case OR_Success: {
6265 // We found a built-in operator or an overloaded operator.
6266 FunctionDecl *FnDecl = Best->Function;
6267
6268 if (FnDecl) {
6269 // We matched an overloaded operator. Build a call to that
6270 // operator.
6271
John McCalla0296f72010-03-19 07:35:19 +00006272 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +00006273
Sebastian Redladba46e2009-10-29 20:17:01 +00006274 // Convert the arguments.
6275 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006276 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006277 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006278 return ExprError();
6279
Anders Carlssona68e51e2010-01-29 18:37:50 +00006280 // Convert the arguments.
6281 OwningExprResult InputInit
6282 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6283 FnDecl->getParamDecl(0)),
6284 SourceLocation(),
6285 Owned(Args[1]));
6286 if (InputInit.isInvalid())
6287 return ExprError();
6288
6289 Args[1] = InputInit.takeAs<Expr>();
6290
Sebastian Redladba46e2009-10-29 20:17:01 +00006291 // Determine the result type
6292 QualType ResultTy
6293 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6294 ResultTy = ResultTy.getNonReferenceType();
6295
6296 // Build the actual expression node.
6297 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6298 LLoc);
6299 UsualUnaryConversions(FnExpr);
6300
6301 Base.release();
6302 Idx.release();
6303 ExprOwningPtr<CXXOperatorCallExpr>
6304 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6305 FnExpr, Args, 2,
6306 ResultTy, RLoc));
6307
6308 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6309 FnDecl))
6310 return ExprError();
6311
6312 return MaybeBindToTemporary(TheCall.release());
6313 } else {
6314 // We matched a built-in operator. Convert the arguments, then
6315 // break out so that we will build the appropriate built-in
6316 // operator node.
6317 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006318 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006319 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006320 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006321 return ExprError();
6322
6323 break;
6324 }
6325 }
6326
6327 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006328 if (CandidateSet.empty())
6329 Diag(LLoc, diag::err_ovl_no_oper)
6330 << Args[0]->getType() << /*subscript*/ 0
6331 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6332 else
6333 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6334 << Args[0]->getType()
6335 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006336 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006337 "[]", LLoc);
6338 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006339 }
6340
6341 case OR_Ambiguous:
6342 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6343 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006344 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006345 "[]", LLoc);
6346 return ExprError();
6347
6348 case OR_Deleted:
6349 Diag(LLoc, diag::err_ovl_deleted_oper)
6350 << Best->Function->isDeleted() << "[]"
6351 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006352 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006353 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006354 return ExprError();
6355 }
6356
6357 // We matched a built-in operator; build it.
6358 Base.release();
6359 Idx.release();
6360 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6361 Owned(Args[1]), RLoc);
6362}
6363
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006364/// BuildCallToMemberFunction - Build a call to a member
6365/// function. MemExpr is the expression that refers to the member
6366/// function (and includes the object parameter), Args/NumArgs are the
6367/// arguments to the function call (not including the object
6368/// parameter). The caller needs to validate that the member
6369/// expression refers to a member function or an overloaded member
6370/// function.
John McCall2d74de92009-12-01 22:10:20 +00006371Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006372Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6373 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006374 unsigned NumArgs, SourceLocation *CommaLocs,
6375 SourceLocation RParenLoc) {
6376 // Dig out the member expression. This holds both the object
6377 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006378 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6379
John McCall10eae182009-11-30 22:42:35 +00006380 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006381 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006382 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006383 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006384 if (isa<MemberExpr>(NakedMemExpr)) {
6385 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006386 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006387 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006388 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006389 } else {
6390 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006391 Qualifier = UnresExpr->getQualifier();
6392
John McCall6e9f8f62009-12-03 04:06:58 +00006393 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006394
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006395 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006396 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006397
John McCall2d74de92009-12-01 22:10:20 +00006398 // FIXME: avoid copy.
6399 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6400 if (UnresExpr->hasExplicitTemplateArgs()) {
6401 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6402 TemplateArgs = &TemplateArgsBuffer;
6403 }
6404
John McCall10eae182009-11-30 22:42:35 +00006405 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6406 E = UnresExpr->decls_end(); I != E; ++I) {
6407
John McCall6e9f8f62009-12-03 04:06:58 +00006408 NamedDecl *Func = *I;
6409 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6410 if (isa<UsingShadowDecl>(Func))
6411 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6412
John McCall10eae182009-11-30 22:42:35 +00006413 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006414 // If explicit template arguments were provided, we can't call a
6415 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006416 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006417 continue;
6418
John McCalla0296f72010-03-19 07:35:19 +00006419 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006420 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006421 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006422 } else {
John McCall10eae182009-11-30 22:42:35 +00006423 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006424 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006425 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006426 CandidateSet,
6427 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006428 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006429 }
Mike Stump11289f42009-09-09 15:08:12 +00006430
John McCall10eae182009-11-30 22:42:35 +00006431 DeclarationName DeclName = UnresExpr->getMemberName();
6432
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006433 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006434 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006435 case OR_Success:
6436 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006437 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006438 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006439 break;
6440
6441 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006442 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006443 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006444 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006445 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006446 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006447 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006448
6449 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006450 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006451 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006452 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006453 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006454 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006455
6456 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006457 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006458 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006459 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006460 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006461 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006462 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006463 }
6464
John McCall16df1e52010-03-30 21:47:33 +00006465 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006466
John McCall2d74de92009-12-01 22:10:20 +00006467 // If overload resolution picked a static member, build a
6468 // non-member call based on that function.
6469 if (Method->isStatic()) {
6470 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6471 Args, NumArgs, RParenLoc);
6472 }
6473
John McCall10eae182009-11-30 22:42:35 +00006474 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006475 }
6476
6477 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006478 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006479 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006480 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006481 Method->getResultType().getNonReferenceType(),
6482 RParenLoc));
6483
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006484 // Check for a valid return type.
6485 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6486 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006487 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006488
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006489 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006490 // We only need to do this if there was actually an overload; otherwise
6491 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006492 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006493 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006494 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6495 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006496 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006497 MemExpr->setBase(ObjectArg);
6498
6499 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006500 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006501 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006502 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006503 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006504
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006505 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006506 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006507
John McCall2d74de92009-12-01 22:10:20 +00006508 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006509}
6510
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006511/// BuildCallToObjectOfClassType - Build a call to an object of class
6512/// type (C++ [over.call.object]), which can end up invoking an
6513/// overloaded function call operator (@c operator()) or performing a
6514/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006515Sema::ExprResult
6516Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006517 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006518 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006519 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006520 SourceLocation RParenLoc) {
6521 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006522 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006523
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006524 // C++ [over.call.object]p1:
6525 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006526 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006527 // candidate functions includes at least the function call
6528 // operators of T. The function call operators of T are obtained by
6529 // ordinary lookup of the name operator() in the context of
6530 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006531 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006532 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006533
6534 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006535 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006536 << Object->getSourceRange()))
6537 return true;
6538
John McCall27b18f82009-11-17 02:14:36 +00006539 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6540 LookupQualifiedName(R, Record->getDecl());
6541 R.suppressDiagnostics();
6542
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006543 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006544 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006545 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006546 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006547 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006548 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006549
Douglas Gregorab7897a2008-11-19 22:57:39 +00006550 // C++ [over.call.object]p2:
6551 // In addition, for each conversion function declared in T of the
6552 // form
6553 //
6554 // operator conversion-type-id () cv-qualifier;
6555 //
6556 // where cv-qualifier is the same cv-qualification as, or a
6557 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006558 // denotes the type "pointer to function of (P1,...,Pn) returning
6559 // R", or the type "reference to pointer to function of
6560 // (P1,...,Pn) returning R", or the type "reference to function
6561 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006562 // is also considered as a candidate function. Similarly,
6563 // surrogate call functions are added to the set of candidate
6564 // functions for each conversion function declared in an
6565 // accessible base class provided the function is not hidden
6566 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006567 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006568 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006569 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006570 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006571 NamedDecl *D = *I;
6572 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6573 if (isa<UsingShadowDecl>(D))
6574 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6575
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006576 // Skip over templated conversion functions; they aren't
6577 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006578 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006579 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006580
John McCall6e9f8f62009-12-03 04:06:58 +00006581 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006582
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006583 // Strip the reference type (if any) and then the pointer type (if
6584 // any) to get down to what might be a function type.
6585 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6586 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6587 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006588
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006589 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006590 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006591 Object->getType(), Args, NumArgs,
6592 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006593 }
Mike Stump11289f42009-09-09 15:08:12 +00006594
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006595 // Perform overload resolution.
6596 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006597 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006598 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006599 // Overload resolution succeeded; we'll build the appropriate call
6600 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006601 break;
6602
6603 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006604 if (CandidateSet.empty())
6605 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6606 << Object->getType() << /*call*/ 1
6607 << Object->getSourceRange();
6608 else
6609 Diag(Object->getSourceRange().getBegin(),
6610 diag::err_ovl_no_viable_object_call)
6611 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006612 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006613 break;
6614
6615 case OR_Ambiguous:
6616 Diag(Object->getSourceRange().getBegin(),
6617 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006618 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006619 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006620 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006621
6622 case OR_Deleted:
6623 Diag(Object->getSourceRange().getBegin(),
6624 diag::err_ovl_deleted_object_call)
6625 << Best->Function->isDeleted()
6626 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006627 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006628 break;
Mike Stump11289f42009-09-09 15:08:12 +00006629 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006630
Douglas Gregorab7897a2008-11-19 22:57:39 +00006631 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006632 // We had an error; delete all of the subexpressions and return
6633 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006634 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006635 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006636 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006637 return true;
6638 }
6639
Douglas Gregorab7897a2008-11-19 22:57:39 +00006640 if (Best->Function == 0) {
6641 // Since there is no function declaration, this is one of the
6642 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006643 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006644 = cast<CXXConversionDecl>(
6645 Best->Conversions[0].UserDefined.ConversionFunction);
6646
John McCalla0296f72010-03-19 07:35:19 +00006647 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006648
Douglas Gregorab7897a2008-11-19 22:57:39 +00006649 // We selected one of the surrogate functions that converts the
6650 // object parameter to a function pointer. Perform the conversion
6651 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006652
6653 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006654 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006655 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6656 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006657
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006658 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006659 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006660 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006661 }
6662
John McCalla0296f72010-03-19 07:35:19 +00006663 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006664
Douglas Gregorab7897a2008-11-19 22:57:39 +00006665 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6666 // that calls this method, using Object for the implicit object
6667 // parameter and passing along the remaining arguments.
6668 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006669 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006670
6671 unsigned NumArgsInProto = Proto->getNumArgs();
6672 unsigned NumArgsToCheck = NumArgs;
6673
6674 // Build the full argument list for the method call (the
6675 // implicit object parameter is placed at the beginning of the
6676 // list).
6677 Expr **MethodArgs;
6678 if (NumArgs < NumArgsInProto) {
6679 NumArgsToCheck = NumArgsInProto;
6680 MethodArgs = new Expr*[NumArgsInProto + 1];
6681 } else {
6682 MethodArgs = new Expr*[NumArgs + 1];
6683 }
6684 MethodArgs[0] = Object;
6685 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6686 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006687
6688 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006689 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006690 UsualUnaryConversions(NewFn);
6691
6692 // Once we've built TheCall, all of the expressions are properly
6693 // owned.
6694 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006695 ExprOwningPtr<CXXOperatorCallExpr>
6696 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006697 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006698 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006699 delete [] MethodArgs;
6700
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006701 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6702 Method))
6703 return true;
6704
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006705 // We may have default arguments. If so, we need to allocate more
6706 // slots in the call for them.
6707 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006708 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006709 else if (NumArgs > NumArgsInProto)
6710 NumArgsToCheck = NumArgsInProto;
6711
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006712 bool IsError = false;
6713
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006714 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006715 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006716 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006717 TheCall->setArg(0, Object);
6718
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006719
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006720 // Check the argument types.
6721 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006722 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006723 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006724 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006725
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006726 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006727
6728 OwningExprResult InputInit
6729 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6730 Method->getParamDecl(i)),
6731 SourceLocation(), Owned(Arg));
6732
6733 IsError |= InputInit.isInvalid();
6734 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006735 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006736 OwningExprResult DefArg
6737 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6738 if (DefArg.isInvalid()) {
6739 IsError = true;
6740 break;
6741 }
6742
6743 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006744 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006745
6746 TheCall->setArg(i + 1, Arg);
6747 }
6748
6749 // If this is a variadic call, handle args passed through "...".
6750 if (Proto->isVariadic()) {
6751 // Promote the arguments (C99 6.5.2.2p7).
6752 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6753 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006754 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006755 TheCall->setArg(i + 1, Arg);
6756 }
6757 }
6758
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006759 if (IsError) return true;
6760
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006761 if (CheckFunctionCall(Method, TheCall.get()))
6762 return true;
6763
Douglas Gregore5e775b2010-04-13 15:50:39 +00006764 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006765}
6766
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006767/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006768/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006769/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006770Sema::OwningExprResult
6771Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6772 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006773 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006774
John McCallbc077cf2010-02-08 23:07:23 +00006775 SourceLocation Loc = Base->getExprLoc();
6776
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006777 // C++ [over.ref]p1:
6778 //
6779 // [...] An expression x->m is interpreted as (x.operator->())->m
6780 // for a class object x of type T if T::operator->() exists and if
6781 // the operator is selected as the best match function by the
6782 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006783 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006784 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006785 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006786
John McCallbc077cf2010-02-08 23:07:23 +00006787 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006788 PDiag(diag::err_typecheck_incomplete_tag)
6789 << Base->getSourceRange()))
6790 return ExprError();
6791
John McCall27b18f82009-11-17 02:14:36 +00006792 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6793 LookupQualifiedName(R, BaseRecord->getDecl());
6794 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006795
6796 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006797 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006798 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006799 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006800 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006801
6802 // Perform overload resolution.
6803 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006804 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006805 case OR_Success:
6806 // Overload resolution succeeded; we'll build the call below.
6807 break;
6808
6809 case OR_No_Viable_Function:
6810 if (CandidateSet.empty())
6811 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006812 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006813 else
6814 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006815 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006816 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006817 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006818
6819 case OR_Ambiguous:
6820 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006821 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006822 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006823 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006824
6825 case OR_Deleted:
6826 Diag(OpLoc, diag::err_ovl_deleted_oper)
6827 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006828 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006829 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006830 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006831 }
6832
John McCalla0296f72010-03-19 07:35:19 +00006833 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6834
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006835 // Convert the object parameter.
6836 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006837 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6838 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006839 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006840
6841 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006842 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006843
6844 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006845 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6846 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006847 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006848
6849 QualType ResultTy = Method->getResultType().getNonReferenceType();
6850 ExprOwningPtr<CXXOperatorCallExpr>
6851 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6852 &Base, 1, ResultTy, OpLoc));
6853
6854 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6855 Method))
6856 return ExprError();
6857 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006858}
6859
Douglas Gregorcd695e52008-11-10 20:40:00 +00006860/// FixOverloadedFunctionReference - E is an expression that refers to
6861/// a C++ overloaded function (possibly with some parentheses and
6862/// perhaps a '&' around it). We have resolved the overloaded function
6863/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006864/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00006865Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00006866 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006867 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006868 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6869 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006870 if (SubExpr == PE->getSubExpr())
6871 return PE->Retain();
6872
6873 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6874 }
6875
6876 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006877 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6878 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006879 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006880 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006881 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006882 if (SubExpr == ICE->getSubExpr())
6883 return ICE->Retain();
6884
6885 return new (Context) ImplicitCastExpr(ICE->getType(),
6886 ICE->getCastKind(),
6887 SubExpr,
6888 ICE->isLvalueCast());
6889 }
6890
6891 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006892 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006893 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006894 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6895 if (Method->isStatic()) {
6896 // Do nothing: static member functions aren't any different
6897 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006898 } else {
John McCalle66edc12009-11-24 19:00:30 +00006899 // Fix the sub expression, which really has to be an
6900 // UnresolvedLookupExpr holding an overloaded member function
6901 // or template.
John McCall16df1e52010-03-30 21:47:33 +00006902 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6903 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00006904 if (SubExpr == UnOp->getSubExpr())
6905 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006906
John McCalld14a8642009-11-21 08:51:07 +00006907 assert(isa<DeclRefExpr>(SubExpr)
6908 && "fixed to something other than a decl ref");
6909 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6910 && "fixed to a member ref with no nested name qualifier");
6911
6912 // We have taken the address of a pointer to member
6913 // function. Perform the computation here so that we get the
6914 // appropriate pointer to member type.
6915 QualType ClassType
6916 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6917 QualType MemPtrType
6918 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6919
6920 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6921 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006922 }
6923 }
John McCall16df1e52010-03-30 21:47:33 +00006924 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6925 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006926 if (SubExpr == UnOp->getSubExpr())
6927 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006928
Douglas Gregor51c538b2009-11-20 19:42:02 +00006929 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6930 Context.getPointerType(SubExpr->getType()),
6931 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006932 }
John McCalld14a8642009-11-21 08:51:07 +00006933
6934 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006935 // FIXME: avoid copy.
6936 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006937 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006938 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6939 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006940 }
6941
John McCalld14a8642009-11-21 08:51:07 +00006942 return DeclRefExpr::Create(Context,
6943 ULE->getQualifier(),
6944 ULE->getQualifierRange(),
6945 Fn,
6946 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006947 Fn->getType(),
6948 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006949 }
6950
John McCall10eae182009-11-30 22:42:35 +00006951 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006952 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006953 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6954 if (MemExpr->hasExplicitTemplateArgs()) {
6955 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6956 TemplateArgs = &TemplateArgsBuffer;
6957 }
John McCall6b51f282009-11-23 01:53:49 +00006958
John McCall2d74de92009-12-01 22:10:20 +00006959 Expr *Base;
6960
6961 // If we're filling in
6962 if (MemExpr->isImplicitAccess()) {
6963 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6964 return DeclRefExpr::Create(Context,
6965 MemExpr->getQualifier(),
6966 MemExpr->getQualifierRange(),
6967 Fn,
6968 MemExpr->getMemberLoc(),
6969 Fn->getType(),
6970 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006971 } else {
6972 SourceLocation Loc = MemExpr->getMemberLoc();
6973 if (MemExpr->getQualifier())
6974 Loc = MemExpr->getQualifierRange().getBegin();
6975 Base = new (Context) CXXThisExpr(Loc,
6976 MemExpr->getBaseType(),
6977 /*isImplicit=*/true);
6978 }
John McCall2d74de92009-12-01 22:10:20 +00006979 } else
6980 Base = MemExpr->getBase()->Retain();
6981
6982 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006983 MemExpr->isArrow(),
6984 MemExpr->getQualifier(),
6985 MemExpr->getQualifierRange(),
6986 Fn,
John McCall16df1e52010-03-30 21:47:33 +00006987 Found,
John McCall6b51f282009-11-23 01:53:49 +00006988 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006989 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006990 Fn->getType());
6991 }
6992
Douglas Gregor51c538b2009-11-20 19:42:02 +00006993 assert(false && "Invalid reference to overloaded function");
6994 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006995}
6996
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006997Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00006998 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006999 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007000 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007001}
7002
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007003} // end namespace clang