blob: 6772672bef195a20cc9b25b9a2c56982eb630f86 [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
1766 // Two implicit conversion sequences of the same form are
1767 // indistinguishable conversion sequences unless one of the
1768 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001769 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001770 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001771 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001772 // User-defined conversion sequence U1 is a better conversion
1773 // sequence than another user-defined conversion sequence U2 if
1774 // they contain the same user-defined conversion function or
1775 // constructor and if the second standard conversion sequence of
1776 // U1 is better than the second standard conversion sequence of
1777 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001778 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001779 ICS2.UserDefined.ConversionFunction)
1780 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1781 ICS2.UserDefined.After);
1782 }
1783
1784 return ImplicitConversionSequence::Indistinguishable;
1785}
1786
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001787// Per 13.3.3.2p3, compare the given standard conversion sequences to
1788// determine if one is a proper subset of the other.
1789static ImplicitConversionSequence::CompareKind
1790compareStandardConversionSubsets(ASTContext &Context,
1791 const StandardConversionSequence& SCS1,
1792 const StandardConversionSequence& SCS2) {
1793 ImplicitConversionSequence::CompareKind Result
1794 = ImplicitConversionSequence::Indistinguishable;
1795
1796 if (SCS1.Second != SCS2.Second) {
1797 if (SCS1.Second == ICK_Identity)
1798 Result = ImplicitConversionSequence::Better;
1799 else if (SCS2.Second == ICK_Identity)
1800 Result = ImplicitConversionSequence::Worse;
1801 else
1802 return ImplicitConversionSequence::Indistinguishable;
1803 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1804 return ImplicitConversionSequence::Indistinguishable;
1805
1806 if (SCS1.Third == SCS2.Third) {
1807 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1808 : ImplicitConversionSequence::Indistinguishable;
1809 }
1810
1811 if (SCS1.Third == ICK_Identity)
1812 return Result == ImplicitConversionSequence::Worse
1813 ? ImplicitConversionSequence::Indistinguishable
1814 : ImplicitConversionSequence::Better;
1815
1816 if (SCS2.Third == ICK_Identity)
1817 return Result == ImplicitConversionSequence::Better
1818 ? ImplicitConversionSequence::Indistinguishable
1819 : ImplicitConversionSequence::Worse;
1820
1821 return ImplicitConversionSequence::Indistinguishable;
1822}
1823
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001824/// CompareStandardConversionSequences - Compare two standard
1825/// conversion sequences to determine whether one is better than the
1826/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001827ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001828Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1829 const StandardConversionSequence& SCS2)
1830{
1831 // Standard conversion sequence S1 is a better conversion sequence
1832 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1833
1834 // -- S1 is a proper subsequence of S2 (comparing the conversion
1835 // sequences in the canonical form defined by 13.3.3.1.1,
1836 // excluding any Lvalue Transformation; the identity conversion
1837 // sequence is considered to be a subsequence of any
1838 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001839 if (ImplicitConversionSequence::CompareKind CK
1840 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1841 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001842
1843 // -- the rank of S1 is better than the rank of S2 (by the rules
1844 // defined below), or, if not that,
1845 ImplicitConversionRank Rank1 = SCS1.getRank();
1846 ImplicitConversionRank Rank2 = SCS2.getRank();
1847 if (Rank1 < Rank2)
1848 return ImplicitConversionSequence::Better;
1849 else if (Rank2 < Rank1)
1850 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001851
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001852 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1853 // are indistinguishable unless one of the following rules
1854 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001855
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001856 // A conversion that is not a conversion of a pointer, or
1857 // pointer to member, to bool is better than another conversion
1858 // that is such a conversion.
1859 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1860 return SCS2.isPointerConversionToBool()
1861 ? ImplicitConversionSequence::Better
1862 : ImplicitConversionSequence::Worse;
1863
Douglas Gregor5c407d92008-10-23 00:40:37 +00001864 // C++ [over.ics.rank]p4b2:
1865 //
1866 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001867 // conversion of B* to A* is better than conversion of B* to
1868 // void*, and conversion of A* to void* is better than conversion
1869 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001870 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001871 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001872 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001873 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001874 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1875 // Exactly one of the conversion sequences is a conversion to
1876 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001877 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1878 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001879 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1880 // Neither conversion sequence converts to a void pointer; compare
1881 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001882 if (ImplicitConversionSequence::CompareKind DerivedCK
1883 = CompareDerivedToBaseConversions(SCS1, SCS2))
1884 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001885 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1886 // Both conversion sequences are conversions to void
1887 // pointers. Compare the source types to determine if there's an
1888 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001889 QualType FromType1 = SCS1.getFromType();
1890 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001891
1892 // Adjust the types we're converting from via the array-to-pointer
1893 // conversion, if we need to.
1894 if (SCS1.First == ICK_Array_To_Pointer)
1895 FromType1 = Context.getArrayDecayedType(FromType1);
1896 if (SCS2.First == ICK_Array_To_Pointer)
1897 FromType2 = Context.getArrayDecayedType(FromType2);
1898
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001899 QualType FromPointee1
1900 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1901 QualType FromPointee2
1902 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001903
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001904 if (IsDerivedFrom(FromPointee2, FromPointee1))
1905 return ImplicitConversionSequence::Better;
1906 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1907 return ImplicitConversionSequence::Worse;
1908
1909 // Objective-C++: If one interface is more specific than the
1910 // other, it is the better one.
1911 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1912 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1913 if (FromIface1 && FromIface1) {
1914 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1915 return ImplicitConversionSequence::Better;
1916 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1917 return ImplicitConversionSequence::Worse;
1918 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001919 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001920
1921 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1922 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001923 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001924 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001925 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001926
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001927 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001928 // C++0x [over.ics.rank]p3b4:
1929 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1930 // implicit object parameter of a non-static member function declared
1931 // without a ref-qualifier, and S1 binds an rvalue reference to an
1932 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001933 // FIXME: We don't know if we're dealing with the implicit object parameter,
1934 // or if the member function in this case has a ref qualifier.
1935 // (Of course, we don't have ref qualifiers yet.)
1936 if (SCS1.RRefBinding != SCS2.RRefBinding)
1937 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1938 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001939
1940 // C++ [over.ics.rank]p3b4:
1941 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1942 // which the references refer are the same type except for
1943 // top-level cv-qualifiers, and the type to which the reference
1944 // initialized by S2 refers is more cv-qualified than the type
1945 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001946 QualType T1 = SCS1.getToType(2);
1947 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001948 T1 = Context.getCanonicalType(T1);
1949 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001950 Qualifiers T1Quals, T2Quals;
1951 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1952 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1953 if (UnqualT1 == UnqualT2) {
1954 // If the type is an array type, promote the element qualifiers to the type
1955 // for comparison.
1956 if (isa<ArrayType>(T1) && T1Quals)
1957 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1958 if (isa<ArrayType>(T2) && T2Quals)
1959 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001960 if (T2.isMoreQualifiedThan(T1))
1961 return ImplicitConversionSequence::Better;
1962 else if (T1.isMoreQualifiedThan(T2))
1963 return ImplicitConversionSequence::Worse;
1964 }
1965 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001966
1967 return ImplicitConversionSequence::Indistinguishable;
1968}
1969
1970/// CompareQualificationConversions - Compares two standard conversion
1971/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001972/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1973ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001974Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001975 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001976 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001977 // -- S1 and S2 differ only in their qualification conversion and
1978 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1979 // cv-qualification signature of type T1 is a proper subset of
1980 // the cv-qualification signature of type T2, and S1 is not the
1981 // deprecated string literal array-to-pointer conversion (4.2).
1982 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1983 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1984 return ImplicitConversionSequence::Indistinguishable;
1985
1986 // FIXME: the example in the standard doesn't use a qualification
1987 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001988 QualType T1 = SCS1.getToType(2);
1989 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001990 T1 = Context.getCanonicalType(T1);
1991 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001992 Qualifiers T1Quals, T2Quals;
1993 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1994 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001995
1996 // If the types are the same, we won't learn anything by unwrapped
1997 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001998 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001999 return ImplicitConversionSequence::Indistinguishable;
2000
Chandler Carruth607f38e2009-12-29 07:16:59 +00002001 // If the type is an array type, promote the element qualifiers to the type
2002 // for comparison.
2003 if (isa<ArrayType>(T1) && T1Quals)
2004 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2005 if (isa<ArrayType>(T2) && T2Quals)
2006 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2007
Mike Stump11289f42009-09-09 15:08:12 +00002008 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002009 = ImplicitConversionSequence::Indistinguishable;
2010 while (UnwrapSimilarPointerTypes(T1, T2)) {
2011 // Within each iteration of the loop, we check the qualifiers to
2012 // determine if this still looks like a qualification
2013 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002014 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002015 // until there are no more pointers or pointers-to-members left
2016 // to unwrap. This essentially mimics what
2017 // IsQualificationConversion does, but here we're checking for a
2018 // strict subset of qualifiers.
2019 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2020 // The qualifiers are the same, so this doesn't tell us anything
2021 // about how the sequences rank.
2022 ;
2023 else if (T2.isMoreQualifiedThan(T1)) {
2024 // T1 has fewer qualifiers, so it could be the better sequence.
2025 if (Result == ImplicitConversionSequence::Worse)
2026 // Neither has qualifiers that are a subset of the other's
2027 // qualifiers.
2028 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002030 Result = ImplicitConversionSequence::Better;
2031 } else if (T1.isMoreQualifiedThan(T2)) {
2032 // T2 has fewer qualifiers, so it could be the better sequence.
2033 if (Result == ImplicitConversionSequence::Better)
2034 // Neither has qualifiers that are a subset of the other's
2035 // qualifiers.
2036 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002037
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002038 Result = ImplicitConversionSequence::Worse;
2039 } else {
2040 // Qualifiers are disjoint.
2041 return ImplicitConversionSequence::Indistinguishable;
2042 }
2043
2044 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002045 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002046 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002047 }
2048
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002049 // Check that the winning standard conversion sequence isn't using
2050 // the deprecated string literal array to pointer conversion.
2051 switch (Result) {
2052 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002053 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002054 Result = ImplicitConversionSequence::Indistinguishable;
2055 break;
2056
2057 case ImplicitConversionSequence::Indistinguishable:
2058 break;
2059
2060 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002061 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002062 Result = ImplicitConversionSequence::Indistinguishable;
2063 break;
2064 }
2065
2066 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002067}
2068
Douglas Gregor5c407d92008-10-23 00:40:37 +00002069/// CompareDerivedToBaseConversions - Compares two standard conversion
2070/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002071/// various kinds of derived-to-base conversions (C++
2072/// [over.ics.rank]p4b3). As part of these checks, we also look at
2073/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002074ImplicitConversionSequence::CompareKind
2075Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2076 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002077 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002078 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002079 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002080 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002081
2082 // Adjust the types we're converting from via the array-to-pointer
2083 // conversion, if we need to.
2084 if (SCS1.First == ICK_Array_To_Pointer)
2085 FromType1 = Context.getArrayDecayedType(FromType1);
2086 if (SCS2.First == ICK_Array_To_Pointer)
2087 FromType2 = Context.getArrayDecayedType(FromType2);
2088
2089 // Canonicalize all of the types.
2090 FromType1 = Context.getCanonicalType(FromType1);
2091 ToType1 = Context.getCanonicalType(ToType1);
2092 FromType2 = Context.getCanonicalType(FromType2);
2093 ToType2 = Context.getCanonicalType(ToType2);
2094
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002095 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002096 //
2097 // If class B is derived directly or indirectly from class A and
2098 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002099 //
2100 // For Objective-C, we let A, B, and C also be Objective-C
2101 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002102
2103 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002104 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002105 SCS2.Second == ICK_Pointer_Conversion &&
2106 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2107 FromType1->isPointerType() && FromType2->isPointerType() &&
2108 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002109 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002110 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002111 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002112 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002113 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002114 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002115 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002116 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002117
John McCall9dd450b2009-09-21 23:43:11 +00002118 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2119 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2120 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2121 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002122
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002123 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002124 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2125 if (IsDerivedFrom(ToPointee1, ToPointee2))
2126 return ImplicitConversionSequence::Better;
2127 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2128 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002129
2130 if (ToIface1 && ToIface2) {
2131 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2132 return ImplicitConversionSequence::Better;
2133 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2134 return ImplicitConversionSequence::Worse;
2135 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002136 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002137
2138 // -- conversion of B* to A* is better than conversion of C* to A*,
2139 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2140 if (IsDerivedFrom(FromPointee2, FromPointee1))
2141 return ImplicitConversionSequence::Better;
2142 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2143 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002144
Douglas Gregor237f96c2008-11-26 23:31:11 +00002145 if (FromIface1 && FromIface2) {
2146 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2147 return ImplicitConversionSequence::Better;
2148 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2149 return ImplicitConversionSequence::Worse;
2150 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002151 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002152 }
2153
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002154 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002155 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2156 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2157 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2158 const MemberPointerType * FromMemPointer1 =
2159 FromType1->getAs<MemberPointerType>();
2160 const MemberPointerType * ToMemPointer1 =
2161 ToType1->getAs<MemberPointerType>();
2162 const MemberPointerType * FromMemPointer2 =
2163 FromType2->getAs<MemberPointerType>();
2164 const MemberPointerType * ToMemPointer2 =
2165 ToType2->getAs<MemberPointerType>();
2166 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2167 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2168 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2169 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2170 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2171 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2172 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2173 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002174 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002175 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2176 if (IsDerivedFrom(ToPointee1, ToPointee2))
2177 return ImplicitConversionSequence::Worse;
2178 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2179 return ImplicitConversionSequence::Better;
2180 }
2181 // conversion of B::* to C::* is better than conversion of A::* to C::*
2182 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2183 if (IsDerivedFrom(FromPointee1, FromPointee2))
2184 return ImplicitConversionSequence::Better;
2185 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2186 return ImplicitConversionSequence::Worse;
2187 }
2188 }
2189
Douglas Gregor5ab11652010-04-17 22:01:05 +00002190 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002191 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002192 // -- binding of an expression of type C to a reference of type
2193 // B& is better than binding an expression of type C to a
2194 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002195 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2196 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002197 if (IsDerivedFrom(ToType1, ToType2))
2198 return ImplicitConversionSequence::Better;
2199 else if (IsDerivedFrom(ToType2, ToType1))
2200 return ImplicitConversionSequence::Worse;
2201 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002202
Douglas Gregor2fe98832008-11-03 19:09:14 +00002203 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002204 // -- binding of an expression of type B to a reference of type
2205 // A& is better than binding an expression of type C to a
2206 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002207 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2208 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002209 if (IsDerivedFrom(FromType2, FromType1))
2210 return ImplicitConversionSequence::Better;
2211 else if (IsDerivedFrom(FromType1, FromType2))
2212 return ImplicitConversionSequence::Worse;
2213 }
2214 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002215
Douglas Gregor5c407d92008-10-23 00:40:37 +00002216 return ImplicitConversionSequence::Indistinguishable;
2217}
2218
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002219/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2220/// determine whether they are reference-related,
2221/// reference-compatible, reference-compatible with added
2222/// qualification, or incompatible, for use in C++ initialization by
2223/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2224/// type, and the first type (T1) is the pointee type of the reference
2225/// type being initialized.
2226Sema::ReferenceCompareResult
2227Sema::CompareReferenceRelationship(SourceLocation Loc,
2228 QualType OrigT1, QualType OrigT2,
2229 bool& DerivedToBase) {
2230 assert(!OrigT1->isReferenceType() &&
2231 "T1 must be the pointee type of the reference type");
2232 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2233
2234 QualType T1 = Context.getCanonicalType(OrigT1);
2235 QualType T2 = Context.getCanonicalType(OrigT2);
2236 Qualifiers T1Quals, T2Quals;
2237 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2238 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2239
2240 // C++ [dcl.init.ref]p4:
2241 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2242 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2243 // T1 is a base class of T2.
2244 if (UnqualT1 == UnqualT2)
2245 DerivedToBase = false;
2246 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
2247 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
2248 IsDerivedFrom(UnqualT2, UnqualT1))
2249 DerivedToBase = true;
2250 else
2251 return Ref_Incompatible;
2252
2253 // At this point, we know that T1 and T2 are reference-related (at
2254 // least).
2255
2256 // If the type is an array type, promote the element qualifiers to the type
2257 // for comparison.
2258 if (isa<ArrayType>(T1) && T1Quals)
2259 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2260 if (isa<ArrayType>(T2) && T2Quals)
2261 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2262
2263 // C++ [dcl.init.ref]p4:
2264 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2265 // reference-related to T2 and cv1 is the same cv-qualification
2266 // as, or greater cv-qualification than, cv2. For purposes of
2267 // overload resolution, cases for which cv1 is greater
2268 // cv-qualification than cv2 are identified as
2269 // reference-compatible with added qualification (see 13.3.3.2).
2270 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2271 return Ref_Compatible;
2272 else if (T1.isMoreQualifiedThan(T2))
2273 return Ref_Compatible_With_Added_Qualification;
2274 else
2275 return Ref_Related;
2276}
2277
2278/// \brief Compute an implicit conversion sequence for reference
2279/// initialization.
2280static ImplicitConversionSequence
2281TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2282 SourceLocation DeclLoc,
2283 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002284 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002285 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2286
2287 // Most paths end in a failed conversion.
2288 ImplicitConversionSequence ICS;
2289 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2290
2291 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2292 QualType T2 = Init->getType();
2293
2294 // If the initializer is the address of an overloaded function, try
2295 // to resolve the overloaded function. If all goes well, T2 is the
2296 // type of the resulting function.
2297 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2298 DeclAccessPair Found;
2299 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2300 false, Found))
2301 T2 = Fn->getType();
2302 }
2303
2304 // Compute some basic properties of the types and the initializer.
2305 bool isRValRef = DeclType->isRValueReferenceType();
2306 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002307 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002308 Sema::ReferenceCompareResult RefRelationship
2309 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2310
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002311
2312 // C++ [over.ics.ref]p3:
2313 // Except for an implicit object parameter, for which see 13.3.1,
2314 // a standard conversion sequence cannot be formed if it requires
2315 // binding an lvalue reference to non-const to an rvalue or
2316 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002317 //
2318 // FIXME: DPG doesn't trust this code. It seems far too early to
2319 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002320 if (isRValRef && InitLvalue == Expr::LV_Valid)
2321 return ICS;
2322
Douglas Gregor870f3742010-04-18 09:22:00 +00002323 // C++0x [dcl.init.ref]p16:
2324 // A reference to type "cv1 T1" is initialized by an expression
2325 // of type "cv2 T2" as follows:
2326
2327 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002328 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2329 // reference-compatible with "cv2 T2," or
2330 //
2331 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2332 if (InitLvalue == Expr::LV_Valid &&
2333 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2334 // C++ [over.ics.ref]p1:
2335 // When a parameter of reference type binds directly (8.5.3)
2336 // to an argument expression, the implicit conversion sequence
2337 // is the identity conversion, unless the argument expression
2338 // has a type that is a derived class of the parameter type,
2339 // in which case the implicit conversion sequence is a
2340 // derived-to-base Conversion (13.3.3.1).
2341 ICS.setStandard();
2342 ICS.Standard.First = ICK_Identity;
2343 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2344 ICS.Standard.Third = ICK_Identity;
2345 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2346 ICS.Standard.setToType(0, T2);
2347 ICS.Standard.setToType(1, T1);
2348 ICS.Standard.setToType(2, T1);
2349 ICS.Standard.ReferenceBinding = true;
2350 ICS.Standard.DirectBinding = true;
2351 ICS.Standard.RRefBinding = false;
2352 ICS.Standard.CopyConstructor = 0;
2353
2354 // Nothing more to do: the inaccessibility/ambiguity check for
2355 // derived-to-base conversions is suppressed when we're
2356 // computing the implicit conversion sequence (C++
2357 // [over.best.ics]p2).
2358 return ICS;
2359 }
2360
2361 // -- has a class type (i.e., T2 is a class type), where T1 is
2362 // not reference-related to T2, and can be implicitly
2363 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2364 // is reference-compatible with "cv3 T3" 92) (this
2365 // conversion is selected by enumerating the applicable
2366 // conversion functions (13.3.1.6) and choosing the best
2367 // one through overload resolution (13.3)),
2368 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2369 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2370 RefRelationship == Sema::Ref_Incompatible) {
2371 CXXRecordDecl *T2RecordDecl
2372 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2373
2374 OverloadCandidateSet CandidateSet(DeclLoc);
2375 const UnresolvedSetImpl *Conversions
2376 = T2RecordDecl->getVisibleConversionFunctions();
2377 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2378 E = Conversions->end(); I != E; ++I) {
2379 NamedDecl *D = *I;
2380 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2381 if (isa<UsingShadowDecl>(D))
2382 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2383
2384 FunctionTemplateDecl *ConvTemplate
2385 = dyn_cast<FunctionTemplateDecl>(D);
2386 CXXConversionDecl *Conv;
2387 if (ConvTemplate)
2388 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2389 else
2390 Conv = cast<CXXConversionDecl>(D);
2391
2392 // If the conversion function doesn't return a reference type,
2393 // it can't be considered for this conversion.
2394 if (Conv->getConversionType()->isLValueReferenceType() &&
2395 (AllowExplicit || !Conv->isExplicit())) {
2396 if (ConvTemplate)
2397 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2398 Init, DeclType, CandidateSet);
2399 else
2400 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2401 DeclType, CandidateSet);
2402 }
2403 }
2404
2405 OverloadCandidateSet::iterator Best;
2406 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2407 case OR_Success:
2408 // C++ [over.ics.ref]p1:
2409 //
2410 // [...] If the parameter binds directly to the result of
2411 // applying a conversion function to the argument
2412 // expression, the implicit conversion sequence is a
2413 // user-defined conversion sequence (13.3.3.1.2), with the
2414 // second standard conversion sequence either an identity
2415 // conversion or, if the conversion function returns an
2416 // entity of a type that is a derived class of the parameter
2417 // type, a derived-to-base Conversion.
2418 if (!Best->FinalConversion.DirectBinding)
2419 break;
2420
2421 ICS.setUserDefined();
2422 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2423 ICS.UserDefined.After = Best->FinalConversion;
2424 ICS.UserDefined.ConversionFunction = Best->Function;
2425 ICS.UserDefined.EllipsisConversion = false;
2426 assert(ICS.UserDefined.After.ReferenceBinding &&
2427 ICS.UserDefined.After.DirectBinding &&
2428 "Expected a direct reference binding!");
2429 return ICS;
2430
2431 case OR_Ambiguous:
2432 ICS.setAmbiguous();
2433 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2434 Cand != CandidateSet.end(); ++Cand)
2435 if (Cand->Viable)
2436 ICS.Ambiguous.addConversion(Cand->Function);
2437 return ICS;
2438
2439 case OR_No_Viable_Function:
2440 case OR_Deleted:
2441 // There was no suitable conversion, or we found a deleted
2442 // conversion; continue with other checks.
2443 break;
2444 }
2445 }
2446
2447 // -- Otherwise, the reference shall be to a non-volatile const
2448 // type (i.e., cv1 shall be const), or the reference shall be an
2449 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002450 //
2451 // We actually handle one oddity of C++ [over.ics.ref] at this
2452 // point, which is that, due to p2 (which short-circuits reference
2453 // binding by only attempting a simple conversion for non-direct
2454 // bindings) and p3's strange wording, we allow a const volatile
2455 // reference to bind to an rvalue. Hence the check for the presence
2456 // of "const" rather than checking for "const" being the only
2457 // qualifier.
2458 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002459 return ICS;
2460
Douglas Gregorf93df192010-04-18 08:46:23 +00002461 // -- if T2 is a class type and
2462 // -- the initializer expression is an rvalue and "cv1 T1"
2463 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002464 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002465 // -- T1 is not reference-related to T2 and the initializer
2466 // expression can be implicitly converted to an rvalue
2467 // of type "cv3 T3" (this conversion is selected by
2468 // enumerating the applicable conversion functions
2469 // (13.3.1.6) and choosing the best one through overload
2470 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002471 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002472 // then the reference is bound to the initializer
2473 // expression rvalue in the first case and to the object
2474 // that is the result of the conversion in the second case
2475 // (or, in either case, to the appropriate base class
2476 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002477 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002478 // We're only checking the first case here, which is a direct
2479 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002480 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2481 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2482 ICS.setStandard();
2483 ICS.Standard.First = ICK_Identity;
2484 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2485 ICS.Standard.Third = ICK_Identity;
2486 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2487 ICS.Standard.setToType(0, T2);
2488 ICS.Standard.setToType(1, T1);
2489 ICS.Standard.setToType(2, T1);
2490 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002491 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002492 ICS.Standard.RRefBinding = isRValRef;
2493 ICS.Standard.CopyConstructor = 0;
2494 return ICS;
2495 }
2496
2497 // -- Otherwise, a temporary of type "cv1 T1" is created and
2498 // initialized from the initializer expression using the
2499 // rules for a non-reference copy initialization (8.5). The
2500 // reference is then bound to the temporary. If T1 is
2501 // reference-related to T2, cv1 must be the same
2502 // cv-qualification as, or greater cv-qualification than,
2503 // cv2; otherwise, the program is ill-formed.
2504 if (RefRelationship == Sema::Ref_Related) {
2505 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2506 // we would be reference-compatible or reference-compatible with
2507 // added qualification. But that wasn't the case, so the reference
2508 // initialization fails.
2509 return ICS;
2510 }
2511
2512 // If at least one of the types is a class type, the types are not
2513 // related, and we aren't allowed any user conversions, the
2514 // reference binding fails. This case is important for breaking
2515 // recursion, since TryImplicitConversion below will attempt to
2516 // create a temporary through the use of a copy constructor.
2517 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2518 (T1->isRecordType() || T2->isRecordType()))
2519 return ICS;
2520
2521 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002522 // When a parameter of reference type is not bound directly to
2523 // an argument expression, the conversion sequence is the one
2524 // required to convert the argument expression to the
2525 // underlying type of the reference according to
2526 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2527 // to copy-initializing a temporary of the underlying type with
2528 // the argument expression. Any difference in top-level
2529 // cv-qualification is subsumed by the initialization itself
2530 // and does not constitute a conversion.
2531 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2532 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002533 /*InOverloadResolution=*/false);
2534
2535 // Of course, that's still a reference binding.
2536 if (ICS.isStandard()) {
2537 ICS.Standard.ReferenceBinding = true;
2538 ICS.Standard.RRefBinding = isRValRef;
2539 } else if (ICS.isUserDefined()) {
2540 ICS.UserDefined.After.ReferenceBinding = true;
2541 ICS.UserDefined.After.RRefBinding = isRValRef;
2542 }
2543 return ICS;
2544}
2545
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002546/// TryCopyInitialization - Try to copy-initialize a value of type
2547/// ToType from the expression From. Return the implicit conversion
2548/// sequence required to pass this argument, which may be a bad
2549/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002550/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002551/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002552static ImplicitConversionSequence
2553TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002554 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002555 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002556 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002557 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002558 /*FIXME:*/From->getLocStart(),
2559 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002560 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002561
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002562 return S.TryImplicitConversion(From, ToType,
2563 SuppressUserConversions,
2564 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002565 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002566}
2567
Douglas Gregor436424c2008-11-18 23:14:02 +00002568/// TryObjectArgumentInitialization - Try to initialize the object
2569/// parameter of the given member function (@c Method) from the
2570/// expression @p From.
2571ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002572Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002573 CXXMethodDecl *Method,
2574 CXXRecordDecl *ActingContext) {
2575 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002576 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2577 // const volatile object.
2578 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2579 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2580 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002581
2582 // Set up the conversion sequence as a "bad" conversion, to allow us
2583 // to exit early.
2584 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002585
2586 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002587 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002588 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002589 FromType = PT->getPointeeType();
2590
2591 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002592
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002593 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002594 // where X is the class of which the function is a member
2595 // (C++ [over.match.funcs]p4). However, when finding an implicit
2596 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002597 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002598 // (C++ [over.match.funcs]p5). We perform a simplified version of
2599 // reference binding here, that allows class rvalues to bind to
2600 // non-constant references.
2601
2602 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2603 // with the implicit object parameter (C++ [over.match.funcs]p5).
2604 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002605 if (ImplicitParamType.getCVRQualifiers()
2606 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002607 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002608 ICS.setBad(BadConversionSequence::bad_qualifiers,
2609 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002610 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002611 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002612
2613 // Check that we have either the same type or a derived type. It
2614 // affects the conversion rank.
2615 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002616 ImplicitConversionKind SecondKind;
2617 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2618 SecondKind = ICK_Identity;
2619 } else if (IsDerivedFrom(FromType, ClassType))
2620 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002621 else {
John McCall65eb8792010-02-25 01:37:24 +00002622 ICS.setBad(BadConversionSequence::unrelated_class,
2623 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002624 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002625 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002626
2627 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002628 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002629 ICS.Standard.setAsIdentityConversion();
2630 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002631 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002632 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002633 ICS.Standard.ReferenceBinding = true;
2634 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002635 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002636 return ICS;
2637}
2638
2639/// PerformObjectArgumentInitialization - Perform initialization of
2640/// the implicit object parameter for the given Method with the given
2641/// expression.
2642bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002643Sema::PerformObjectArgumentInitialization(Expr *&From,
2644 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002645 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002646 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002647 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002648 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002649 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002650
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002651 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002652 FromRecordType = PT->getPointeeType();
2653 DestType = Method->getThisType(Context);
2654 } else {
2655 FromRecordType = From->getType();
2656 DestType = ImplicitParamRecordType;
2657 }
2658
John McCall6e9f8f62009-12-03 04:06:58 +00002659 // Note that we always use the true parent context when performing
2660 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002661 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002662 = TryObjectArgumentInitialization(From->getType(), Method,
2663 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002664 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002665 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002666 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002667 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002668
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002669 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002670 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002671
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002672 if (!Context.hasSameType(From->getType(), DestType))
2673 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2674 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002675 return false;
2676}
2677
Douglas Gregor5fb53972009-01-14 15:45:31 +00002678/// TryContextuallyConvertToBool - Attempt to contextually convert the
2679/// expression From to bool (C++0x [conv]p3).
2680ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002681 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002682 // FIXME: Are these flags correct?
2683 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002684 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002685 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002686}
2687
2688/// PerformContextuallyConvertToBool - Perform a contextual conversion
2689/// of the expression From to bool (C++0x [conv]p3).
2690bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2691 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002692 if (!ICS.isBad())
2693 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002694
Fariborz Jahanian76197412009-11-18 18:26:29 +00002695 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002696 return Diag(From->getSourceRange().getBegin(),
2697 diag::err_typecheck_bool_condition)
2698 << From->getType() << From->getSourceRange();
2699 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002700}
2701
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002702/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002703/// candidate functions, using the given function call arguments. If
2704/// @p SuppressUserConversions, then don't allow user-defined
2705/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002706///
2707/// \para PartialOverloading true if we are performing "partial" overloading
2708/// based on an incomplete set of function arguments. This feature is used by
2709/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002710void
2711Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002712 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002713 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002714 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002715 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002716 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002717 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002718 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002719 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002720 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002721 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002722
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002723 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002724 if (!isa<CXXConstructorDecl>(Method)) {
2725 // If we get here, it's because we're calling a member function
2726 // that is named without a member access expression (e.g.,
2727 // "this->f") that was either written explicitly or created
2728 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002729 // function, e.g., X::f(). We use an empty type for the implied
2730 // object argument (C++ [over.call.func]p3), and the acting context
2731 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002732 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002733 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002734 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002735 return;
2736 }
2737 // We treat a constructor like a non-member function, since its object
2738 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002739 }
2740
Douglas Gregorff7028a2009-11-13 23:59:09 +00002741 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002742 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002743
Douglas Gregor27381f32009-11-23 12:27:39 +00002744 // Overload resolution is always an unevaluated context.
2745 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2746
Douglas Gregorffe14e32009-11-14 01:20:54 +00002747 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2748 // C++ [class.copy]p3:
2749 // A member function template is never instantiated to perform the copy
2750 // of a class object to an object of its class type.
2751 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2752 if (NumArgs == 1 &&
2753 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002754 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2755 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002756 return;
2757 }
2758
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002759 // Add this candidate
2760 CandidateSet.push_back(OverloadCandidate());
2761 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002762 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002763 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002764 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002765 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002766 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002767
2768 unsigned NumArgsInProto = Proto->getNumArgs();
2769
2770 // (C++ 13.3.2p2): A candidate function having fewer than m
2771 // parameters is viable only if it has an ellipsis in its parameter
2772 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002773 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2774 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002775 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002776 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002777 return;
2778 }
2779
2780 // (C++ 13.3.2p2): A candidate function having more than m parameters
2781 // is viable only if the (m+1)st parameter has a default argument
2782 // (8.3.6). For the purposes of overload resolution, the
2783 // parameter list is truncated on the right, so that there are
2784 // exactly m parameters.
2785 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002786 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002787 // Not enough arguments.
2788 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002789 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002790 return;
2791 }
2792
2793 // Determine the implicit conversion sequences for each of the
2794 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002795 Candidate.Conversions.resize(NumArgs);
2796 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2797 if (ArgIdx < NumArgsInProto) {
2798 // (C++ 13.3.2p3): for F to be a viable function, there shall
2799 // exist for each argument an implicit conversion sequence
2800 // (13.3.3.1) that converts that argument to the corresponding
2801 // parameter of F.
2802 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002803 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002804 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002805 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00002806 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002807 if (Candidate.Conversions[ArgIdx].isBad()) {
2808 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002809 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002810 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002811 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002812 } else {
2813 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2814 // argument for which there is no corresponding parameter is
2815 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002816 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002817 }
2818 }
2819}
2820
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002821/// \brief Add all of the function declarations in the given function set to
2822/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002823void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002824 Expr **Args, unsigned NumArgs,
2825 OverloadCandidateSet& CandidateSet,
2826 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002827 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00002828 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2829 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002830 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002831 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002832 cast<CXXMethodDecl>(FD)->getParent(),
2833 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002834 CandidateSet, SuppressUserConversions);
2835 else
John McCalla0296f72010-03-19 07:35:19 +00002836 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002837 SuppressUserConversions);
2838 } else {
John McCalla0296f72010-03-19 07:35:19 +00002839 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002840 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2841 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002842 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002843 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002844 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002845 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002846 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002847 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002848 else
John McCalla0296f72010-03-19 07:35:19 +00002849 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00002850 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002851 Args, NumArgs, CandidateSet,
2852 SuppressUserConversions);
2853 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002854 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002855}
2856
John McCallf0f1cf02009-11-17 07:50:12 +00002857/// AddMethodCandidate - Adds a named decl (which is some kind of
2858/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00002859void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002860 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002861 Expr **Args, unsigned NumArgs,
2862 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002863 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00002864 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002865 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002866
2867 if (isa<UsingShadowDecl>(Decl))
2868 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2869
2870 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2871 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2872 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00002873 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2874 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002875 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002876 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002877 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002878 } else {
John McCalla0296f72010-03-19 07:35:19 +00002879 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002880 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002881 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002882 }
2883}
2884
Douglas Gregor436424c2008-11-18 23:14:02 +00002885/// AddMethodCandidate - Adds the given C++ member function to the set
2886/// of candidate functions, using the given function call arguments
2887/// and the object argument (@c Object). For example, in a call
2888/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2889/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2890/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00002891/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00002892void
John McCalla0296f72010-03-19 07:35:19 +00002893Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002894 CXXRecordDecl *ActingContext, QualType ObjectType,
2895 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002896 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002897 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002898 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002899 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002900 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002901 assert(!isa<CXXConstructorDecl>(Method) &&
2902 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002903
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002904 if (!CandidateSet.isNewCandidate(Method))
2905 return;
2906
Douglas Gregor27381f32009-11-23 12:27:39 +00002907 // Overload resolution is always an unevaluated context.
2908 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2909
Douglas Gregor436424c2008-11-18 23:14:02 +00002910 // Add this candidate
2911 CandidateSet.push_back(OverloadCandidate());
2912 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002913 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00002914 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002915 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002916 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002917
2918 unsigned NumArgsInProto = Proto->getNumArgs();
2919
2920 // (C++ 13.3.2p2): A candidate function having fewer than m
2921 // parameters is viable only if it has an ellipsis in its parameter
2922 // list (8.3.5).
2923 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2924 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002925 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002926 return;
2927 }
2928
2929 // (C++ 13.3.2p2): A candidate function having more than m parameters
2930 // is viable only if the (m+1)st parameter has a default argument
2931 // (8.3.6). For the purposes of overload resolution, the
2932 // parameter list is truncated on the right, so that there are
2933 // exactly m parameters.
2934 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2935 if (NumArgs < MinRequiredArgs) {
2936 // Not enough arguments.
2937 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002938 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002939 return;
2940 }
2941
2942 Candidate.Viable = true;
2943 Candidate.Conversions.resize(NumArgs + 1);
2944
John McCall6e9f8f62009-12-03 04:06:58 +00002945 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002946 // The implicit object argument is ignored.
2947 Candidate.IgnoreObjectArgument = true;
2948 else {
2949 // Determine the implicit conversion sequence for the object
2950 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002951 Candidate.Conversions[0]
2952 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002953 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002954 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002955 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002956 return;
2957 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002958 }
2959
2960 // Determine the implicit conversion sequences for each of the
2961 // arguments.
2962 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2963 if (ArgIdx < NumArgsInProto) {
2964 // (C++ 13.3.2p3): for F to be a viable function, there shall
2965 // exist for each argument an implicit conversion sequence
2966 // (13.3.3.1) that converts that argument to the corresponding
2967 // parameter of F.
2968 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002969 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002970 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002971 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00002972 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002973 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002974 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002975 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002976 break;
2977 }
2978 } else {
2979 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2980 // argument for which there is no corresponding parameter is
2981 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002982 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002983 }
2984 }
2985}
2986
Douglas Gregor97628d62009-08-21 00:16:32 +00002987/// \brief Add a C++ member function template as a candidate to the candidate
2988/// set, using template argument deduction to produce an appropriate member
2989/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002990void
Douglas Gregor97628d62009-08-21 00:16:32 +00002991Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00002992 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002993 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002994 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002995 QualType ObjectType,
2996 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002997 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002998 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002999 if (!CandidateSet.isNewCandidate(MethodTmpl))
3000 return;
3001
Douglas Gregor97628d62009-08-21 00:16:32 +00003002 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003003 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003004 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003005 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003006 // candidate functions in the usual way.113) A given name can refer to one
3007 // or more function templates and also to a set of overloaded non-template
3008 // functions. In such a case, the candidate functions generated from each
3009 // function template are combined with the set of non-template candidate
3010 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003011 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003012 FunctionDecl *Specialization = 0;
3013 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003014 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003015 Args, NumArgs, Specialization, Info)) {
3016 // FIXME: Record what happened with template argument deduction, so
3017 // that we can give the user a beautiful diagnostic.
3018 (void)Result;
3019 return;
3020 }
Mike Stump11289f42009-09-09 15:08:12 +00003021
Douglas Gregor97628d62009-08-21 00:16:32 +00003022 // Add the function template specialization produced by template argument
3023 // deduction as a candidate.
3024 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003025 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003026 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003027 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003028 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003029 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003030}
3031
Douglas Gregor05155d82009-08-21 23:19:43 +00003032/// \brief Add a C++ function template specialization as a candidate
3033/// in the candidate set, using template argument deduction to produce
3034/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003035void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003036Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003037 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003038 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003039 Expr **Args, unsigned NumArgs,
3040 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003041 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003042 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3043 return;
3044
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003045 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003046 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003047 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003048 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003049 // candidate functions in the usual way.113) A given name can refer to one
3050 // or more function templates and also to a set of overloaded non-template
3051 // functions. In such a case, the candidate functions generated from each
3052 // function template are combined with the set of non-template candidate
3053 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003054 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003055 FunctionDecl *Specialization = 0;
3056 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003057 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003058 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003059 CandidateSet.push_back(OverloadCandidate());
3060 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003061 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003062 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3063 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003064 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003065 Candidate.IsSurrogate = false;
3066 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00003067
3068 // TODO: record more information about failed template arguments
3069 Candidate.DeductionFailure.Result = Result;
3070 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003071 return;
3072 }
Mike Stump11289f42009-09-09 15:08:12 +00003073
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003074 // Add the function template specialization produced by template argument
3075 // deduction as a candidate.
3076 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003077 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003078 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003079}
Mike Stump11289f42009-09-09 15:08:12 +00003080
Douglas Gregora1f013e2008-11-07 22:36:19 +00003081/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003082/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003083/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003084/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003085/// (which may or may not be the same type as the type that the
3086/// conversion function produces).
3087void
3088Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003089 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003090 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003091 Expr *From, QualType ToType,
3092 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003093 assert(!Conversion->getDescribedFunctionTemplate() &&
3094 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003095 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003096 if (!CandidateSet.isNewCandidate(Conversion))
3097 return;
3098
Douglas Gregor27381f32009-11-23 12:27:39 +00003099 // Overload resolution is always an unevaluated context.
3100 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3101
Douglas Gregora1f013e2008-11-07 22:36:19 +00003102 // Add this candidate
3103 CandidateSet.push_back(OverloadCandidate());
3104 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003105 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003106 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003107 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003108 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003109 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003110 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003111 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003112
Douglas Gregor436424c2008-11-18 23:14:02 +00003113 // Determine the implicit conversion sequence for the implicit
3114 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003115 Candidate.Viable = true;
3116 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003117 Candidate.Conversions[0]
3118 = TryObjectArgumentInitialization(From->getType(), Conversion,
3119 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003120 // Conversion functions to a different type in the base class is visible in
3121 // the derived class. So, a derived to base conversion should not participate
3122 // in overload resolution.
3123 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3124 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003125 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003126 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003127 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003128 return;
3129 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003130
3131 // We won't go through a user-define type conversion function to convert a
3132 // derived to base as such conversions are given Conversion Rank. They only
3133 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3134 QualType FromCanon
3135 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3136 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3137 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3138 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003139 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003140 return;
3141 }
3142
Douglas Gregora1f013e2008-11-07 22:36:19 +00003143 // To determine what the conversion from the result of calling the
3144 // conversion function to the type we're eventually trying to
3145 // convert to (ToType), we need to synthesize a call to the
3146 // conversion function and attempt copy initialization from it. This
3147 // makes sure that we get the right semantics with respect to
3148 // lvalues/rvalues and the type. Fortunately, we can allocate this
3149 // call on the stack and we don't need its arguments to be
3150 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003151 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003152 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003153 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003154 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00003155 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00003156
3157 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003158 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3159 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003160 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003161 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003162 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003163 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003164 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003165 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003166 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003167
John McCall0d1da222010-01-12 00:44:57 +00003168 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003169 case ImplicitConversionSequence::StandardConversion:
3170 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003171
3172 // C++ [over.ics.user]p3:
3173 // If the user-defined conversion is specified by a specialization of a
3174 // conversion function template, the second standard conversion sequence
3175 // shall have exact match rank.
3176 if (Conversion->getPrimaryTemplate() &&
3177 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3178 Candidate.Viable = false;
3179 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3180 }
3181
Douglas Gregora1f013e2008-11-07 22:36:19 +00003182 break;
3183
3184 case ImplicitConversionSequence::BadConversion:
3185 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003186 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003187 break;
3188
3189 default:
Mike Stump11289f42009-09-09 15:08:12 +00003190 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003191 "Can only end up with a standard conversion sequence or failure");
3192 }
3193}
3194
Douglas Gregor05155d82009-08-21 23:19:43 +00003195/// \brief Adds a conversion function template specialization
3196/// candidate to the overload set, using template argument deduction
3197/// to deduce the template arguments of the conversion function
3198/// template from the type that we are converting to (C++
3199/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003200void
Douglas Gregor05155d82009-08-21 23:19:43 +00003201Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003202 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003203 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003204 Expr *From, QualType ToType,
3205 OverloadCandidateSet &CandidateSet) {
3206 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3207 "Only conversion function templates permitted here");
3208
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003209 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3210 return;
3211
John McCallbc077cf2010-02-08 23:07:23 +00003212 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003213 CXXConversionDecl *Specialization = 0;
3214 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003215 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003216 Specialization, Info)) {
3217 // FIXME: Record what happened with template argument deduction, so
3218 // that we can give the user a beautiful diagnostic.
3219 (void)Result;
3220 return;
3221 }
Mike Stump11289f42009-09-09 15:08:12 +00003222
Douglas Gregor05155d82009-08-21 23:19:43 +00003223 // Add the conversion function template specialization produced by
3224 // template argument deduction as a candidate.
3225 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003226 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003227 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003228}
3229
Douglas Gregorab7897a2008-11-19 22:57:39 +00003230/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3231/// converts the given @c Object to a function pointer via the
3232/// conversion function @c Conversion, and then attempts to call it
3233/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3234/// the type of function that we'll eventually be calling.
3235void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003236 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003237 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003238 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003239 QualType ObjectType,
3240 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003241 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003242 if (!CandidateSet.isNewCandidate(Conversion))
3243 return;
3244
Douglas Gregor27381f32009-11-23 12:27:39 +00003245 // Overload resolution is always an unevaluated context.
3246 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3247
Douglas Gregorab7897a2008-11-19 22:57:39 +00003248 CandidateSet.push_back(OverloadCandidate());
3249 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003250 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003251 Candidate.Function = 0;
3252 Candidate.Surrogate = Conversion;
3253 Candidate.Viable = true;
3254 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003255 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003256 Candidate.Conversions.resize(NumArgs + 1);
3257
3258 // Determine the implicit conversion sequence for the implicit
3259 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003260 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003261 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003262 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003263 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003264 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003265 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003266 return;
3267 }
3268
3269 // The first conversion is actually a user-defined conversion whose
3270 // first conversion is ObjectInit's standard conversion (which is
3271 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003272 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003273 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003274 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003275 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003276 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003277 = Candidate.Conversions[0].UserDefined.Before;
3278 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3279
Mike Stump11289f42009-09-09 15:08:12 +00003280 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003281 unsigned NumArgsInProto = Proto->getNumArgs();
3282
3283 // (C++ 13.3.2p2): A candidate function having fewer than m
3284 // parameters is viable only if it has an ellipsis in its parameter
3285 // list (8.3.5).
3286 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3287 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003288 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003289 return;
3290 }
3291
3292 // Function types don't have any default arguments, so just check if
3293 // we have enough arguments.
3294 if (NumArgs < NumArgsInProto) {
3295 // Not enough arguments.
3296 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003297 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003298 return;
3299 }
3300
3301 // Determine the implicit conversion sequences for each of the
3302 // arguments.
3303 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3304 if (ArgIdx < NumArgsInProto) {
3305 // (C++ 13.3.2p3): for F to be a viable function, there shall
3306 // exist for each argument an implicit conversion sequence
3307 // (13.3.3.1) that converts that argument to the corresponding
3308 // parameter of F.
3309 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003310 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003311 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003312 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003313 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003314 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003315 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003316 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003317 break;
3318 }
3319 } else {
3320 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3321 // argument for which there is no corresponding parameter is
3322 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003323 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003324 }
3325 }
3326}
3327
Mike Stump87c57ac2009-05-16 07:39:55 +00003328// FIXME: This will eventually be removed, once we've migrated all of the
3329// operator overloading logic over to the scheme used by binary operators, which
3330// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003331void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003332 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003333 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003334 OverloadCandidateSet& CandidateSet,
3335 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003336 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003337
3338 QualType T1 = Args[0]->getType();
3339 QualType T2;
3340 if (NumArgs > 1)
3341 T2 = Args[1]->getType();
3342
3343 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003344 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003345 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3346 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3347 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3348 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003349 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003350 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003351}
3352
3353/// \brief Add overload candidates for overloaded operators that are
3354/// member functions.
3355///
3356/// Add the overloaded operator candidates that are member functions
3357/// for the operator Op that was used in an operator expression such
3358/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3359/// CandidateSet will store the added overload candidates. (C++
3360/// [over.match.oper]).
3361void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3362 SourceLocation OpLoc,
3363 Expr **Args, unsigned NumArgs,
3364 OverloadCandidateSet& CandidateSet,
3365 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003366 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3367
3368 // C++ [over.match.oper]p3:
3369 // For a unary operator @ with an operand of a type whose
3370 // cv-unqualified version is T1, and for a binary operator @ with
3371 // a left operand of a type whose cv-unqualified version is T1 and
3372 // a right operand of a type whose cv-unqualified version is T2,
3373 // three sets of candidate functions, designated member
3374 // candidates, non-member candidates and built-in candidates, are
3375 // constructed as follows:
3376 QualType T1 = Args[0]->getType();
3377 QualType T2;
3378 if (NumArgs > 1)
3379 T2 = Args[1]->getType();
3380
3381 // -- If T1 is a class type, the set of member candidates is the
3382 // result of the qualified lookup of T1::operator@
3383 // (13.3.1.1.1); otherwise, the set of member candidates is
3384 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003385 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003386 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003387 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003388 return;
Mike Stump11289f42009-09-09 15:08:12 +00003389
John McCall27b18f82009-11-17 02:14:36 +00003390 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3391 LookupQualifiedName(Operators, T1Rec->getDecl());
3392 Operators.suppressDiagnostics();
3393
Mike Stump11289f42009-09-09 15:08:12 +00003394 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003395 OperEnd = Operators.end();
3396 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003397 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003398 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003399 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003400 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003401 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003402}
3403
Douglas Gregora11693b2008-11-12 17:17:38 +00003404/// AddBuiltinCandidate - Add a candidate for a built-in
3405/// operator. ResultTy and ParamTys are the result and parameter types
3406/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003407/// arguments being passed to the candidate. IsAssignmentOperator
3408/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003409/// operator. NumContextualBoolArguments is the number of arguments
3410/// (at the beginning of the argument list) that will be contextually
3411/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003412void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003413 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003414 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003415 bool IsAssignmentOperator,
3416 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003417 // Overload resolution is always an unevaluated context.
3418 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3419
Douglas Gregora11693b2008-11-12 17:17:38 +00003420 // Add this candidate
3421 CandidateSet.push_back(OverloadCandidate());
3422 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003423 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003424 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003425 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003426 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003427 Candidate.BuiltinTypes.ResultTy = ResultTy;
3428 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3429 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3430
3431 // Determine the implicit conversion sequences for each of the
3432 // arguments.
3433 Candidate.Viable = true;
3434 Candidate.Conversions.resize(NumArgs);
3435 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003436 // C++ [over.match.oper]p4:
3437 // For the built-in assignment operators, conversions of the
3438 // left operand are restricted as follows:
3439 // -- no temporaries are introduced to hold the left operand, and
3440 // -- no user-defined conversions are applied to the left
3441 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003442 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003443 //
3444 // We block these conversions by turning off user-defined
3445 // conversions, since that is the only way that initialization of
3446 // a reference to a non-class type can occur from something that
3447 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003448 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003449 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003450 "Contextual conversion to bool requires bool type");
3451 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3452 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003453 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003454 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003455 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003456 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003457 }
John McCall0d1da222010-01-12 00:44:57 +00003458 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003459 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003460 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003461 break;
3462 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003463 }
3464}
3465
3466/// BuiltinCandidateTypeSet - A set of types that will be used for the
3467/// candidate operator functions for built-in operators (C++
3468/// [over.built]). The types are separated into pointer types and
3469/// enumeration types.
3470class BuiltinCandidateTypeSet {
3471 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003472 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003473
3474 /// PointerTypes - The set of pointer types that will be used in the
3475 /// built-in candidates.
3476 TypeSet PointerTypes;
3477
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003478 /// MemberPointerTypes - The set of member pointer types that will be
3479 /// used in the built-in candidates.
3480 TypeSet MemberPointerTypes;
3481
Douglas Gregora11693b2008-11-12 17:17:38 +00003482 /// EnumerationTypes - The set of enumeration types that will be
3483 /// used in the built-in candidates.
3484 TypeSet EnumerationTypes;
3485
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003486 /// Sema - The semantic analysis instance where we are building the
3487 /// candidate type set.
3488 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003489
Douglas Gregora11693b2008-11-12 17:17:38 +00003490 /// Context - The AST context in which we will build the type sets.
3491 ASTContext &Context;
3492
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003493 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3494 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003495 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003496
3497public:
3498 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003499 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003500
Mike Stump11289f42009-09-09 15:08:12 +00003501 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003502 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003503
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003504 void AddTypesConvertedFrom(QualType Ty,
3505 SourceLocation Loc,
3506 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003507 bool AllowExplicitConversions,
3508 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003509
3510 /// pointer_begin - First pointer type found;
3511 iterator pointer_begin() { return PointerTypes.begin(); }
3512
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003513 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003514 iterator pointer_end() { return PointerTypes.end(); }
3515
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003516 /// member_pointer_begin - First member pointer type found;
3517 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3518
3519 /// member_pointer_end - Past the last member pointer type found;
3520 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3521
Douglas Gregora11693b2008-11-12 17:17:38 +00003522 /// enumeration_begin - First enumeration type found;
3523 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3524
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003525 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003526 iterator enumeration_end() { return EnumerationTypes.end(); }
3527};
3528
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003529/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003530/// the set of pointer types along with any more-qualified variants of
3531/// that type. For example, if @p Ty is "int const *", this routine
3532/// will add "int const *", "int const volatile *", "int const
3533/// restrict *", and "int const volatile restrict *" to the set of
3534/// pointer types. Returns true if the add of @p Ty itself succeeded,
3535/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003536///
3537/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003538bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003539BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3540 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003541
Douglas Gregora11693b2008-11-12 17:17:38 +00003542 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003543 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003544 return false;
3545
John McCall8ccfcb52009-09-24 19:53:00 +00003546 const PointerType *PointerTy = Ty->getAs<PointerType>();
3547 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003548
John McCall8ccfcb52009-09-24 19:53:00 +00003549 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003550 // Don't add qualified variants of arrays. For one, they're not allowed
3551 // (the qualifier would sink to the element type), and for another, the
3552 // only overload situation where it matters is subscript or pointer +- int,
3553 // and those shouldn't have qualifier variants anyway.
3554 if (PointeeTy->isArrayType())
3555 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003556 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003557 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003558 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003559 bool hasVolatile = VisibleQuals.hasVolatile();
3560 bool hasRestrict = VisibleQuals.hasRestrict();
3561
John McCall8ccfcb52009-09-24 19:53:00 +00003562 // Iterate through all strict supersets of BaseCVR.
3563 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3564 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003565 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3566 // in the types.
3567 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3568 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003569 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3570 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003571 }
3572
3573 return true;
3574}
3575
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003576/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3577/// to the set of pointer types along with any more-qualified variants of
3578/// that type. For example, if @p Ty is "int const *", this routine
3579/// will add "int const *", "int const volatile *", "int const
3580/// restrict *", and "int const volatile restrict *" to the set of
3581/// pointer types. Returns true if the add of @p Ty itself succeeded,
3582/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003583///
3584/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003585bool
3586BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3587 QualType Ty) {
3588 // Insert this type.
3589 if (!MemberPointerTypes.insert(Ty))
3590 return false;
3591
John McCall8ccfcb52009-09-24 19:53:00 +00003592 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3593 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003594
John McCall8ccfcb52009-09-24 19:53:00 +00003595 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003596 // Don't add qualified variants of arrays. For one, they're not allowed
3597 // (the qualifier would sink to the element type), and for another, the
3598 // only overload situation where it matters is subscript or pointer +- int,
3599 // and those shouldn't have qualifier variants anyway.
3600 if (PointeeTy->isArrayType())
3601 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003602 const Type *ClassTy = PointerTy->getClass();
3603
3604 // Iterate through all strict supersets of the pointee type's CVR
3605 // qualifiers.
3606 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3607 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3608 if ((CVR | BaseCVR) != CVR) continue;
3609
3610 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3611 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003612 }
3613
3614 return true;
3615}
3616
Douglas Gregora11693b2008-11-12 17:17:38 +00003617/// AddTypesConvertedFrom - Add each of the types to which the type @p
3618/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003619/// primarily interested in pointer types and enumeration types. We also
3620/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003621/// AllowUserConversions is true if we should look at the conversion
3622/// functions of a class type, and AllowExplicitConversions if we
3623/// should also include the explicit conversion functions of a class
3624/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003625void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003626BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003627 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003628 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003629 bool AllowExplicitConversions,
3630 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003631 // Only deal with canonical types.
3632 Ty = Context.getCanonicalType(Ty);
3633
3634 // Look through reference types; they aren't part of the type of an
3635 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003636 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003637 Ty = RefTy->getPointeeType();
3638
3639 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003640 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003641
Sebastian Redl65ae2002009-11-05 16:36:20 +00003642 // If we're dealing with an array type, decay to the pointer.
3643 if (Ty->isArrayType())
3644 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3645
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003646 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003647 QualType PointeeTy = PointerTy->getPointeeType();
3648
3649 // Insert our type, and its more-qualified variants, into the set
3650 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003651 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003652 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003653 } else if (Ty->isMemberPointerType()) {
3654 // Member pointers are far easier, since the pointee can't be converted.
3655 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3656 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003657 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003658 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003659 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003660 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003661 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003662 // No conversion functions in incomplete types.
3663 return;
3664 }
Mike Stump11289f42009-09-09 15:08:12 +00003665
Douglas Gregora11693b2008-11-12 17:17:38 +00003666 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003667 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003668 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003669 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003670 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003671 NamedDecl *D = I.getDecl();
3672 if (isa<UsingShadowDecl>(D))
3673 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003674
Mike Stump11289f42009-09-09 15:08:12 +00003675 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003676 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003677 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003678 continue;
3679
John McCallda4458e2010-03-31 01:36:47 +00003680 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003681 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003682 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003683 VisibleQuals);
3684 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003685 }
3686 }
3687 }
3688}
3689
Douglas Gregor84605ae2009-08-24 13:43:27 +00003690/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3691/// the volatile- and non-volatile-qualified assignment operators for the
3692/// given type to the candidate set.
3693static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3694 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003695 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003696 unsigned NumArgs,
3697 OverloadCandidateSet &CandidateSet) {
3698 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003699
Douglas Gregor84605ae2009-08-24 13:43:27 +00003700 // T& operator=(T&, T)
3701 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3702 ParamTypes[1] = T;
3703 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3704 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003705
Douglas Gregor84605ae2009-08-24 13:43:27 +00003706 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3707 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003708 ParamTypes[0]
3709 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003710 ParamTypes[1] = T;
3711 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003712 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003713 }
3714}
Mike Stump11289f42009-09-09 15:08:12 +00003715
Sebastian Redl1054fae2009-10-25 17:03:50 +00003716/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3717/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003718static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3719 Qualifiers VRQuals;
3720 const RecordType *TyRec;
3721 if (const MemberPointerType *RHSMPType =
3722 ArgExpr->getType()->getAs<MemberPointerType>())
3723 TyRec = cast<RecordType>(RHSMPType->getClass());
3724 else
3725 TyRec = ArgExpr->getType()->getAs<RecordType>();
3726 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003727 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003728 VRQuals.addVolatile();
3729 VRQuals.addRestrict();
3730 return VRQuals;
3731 }
3732
3733 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003734 if (!ClassDecl->hasDefinition())
3735 return VRQuals;
3736
John McCallad371252010-01-20 00:46:10 +00003737 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003738 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003739
John McCallad371252010-01-20 00:46:10 +00003740 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003741 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003742 NamedDecl *D = I.getDecl();
3743 if (isa<UsingShadowDecl>(D))
3744 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3745 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003746 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3747 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3748 CanTy = ResTypeRef->getPointeeType();
3749 // Need to go down the pointer/mempointer chain and add qualifiers
3750 // as see them.
3751 bool done = false;
3752 while (!done) {
3753 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3754 CanTy = ResTypePtr->getPointeeType();
3755 else if (const MemberPointerType *ResTypeMPtr =
3756 CanTy->getAs<MemberPointerType>())
3757 CanTy = ResTypeMPtr->getPointeeType();
3758 else
3759 done = true;
3760 if (CanTy.isVolatileQualified())
3761 VRQuals.addVolatile();
3762 if (CanTy.isRestrictQualified())
3763 VRQuals.addRestrict();
3764 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3765 return VRQuals;
3766 }
3767 }
3768 }
3769 return VRQuals;
3770}
3771
Douglas Gregord08452f2008-11-19 15:42:04 +00003772/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3773/// operator overloads to the candidate set (C++ [over.built]), based
3774/// on the operator @p Op and the arguments given. For example, if the
3775/// operator is a binary '+', this routine might add "int
3776/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003777void
Mike Stump11289f42009-09-09 15:08:12 +00003778Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003779 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003780 Expr **Args, unsigned NumArgs,
3781 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003782 // The set of "promoted arithmetic types", which are the arithmetic
3783 // types are that preserved by promotion (C++ [over.built]p2). Note
3784 // that the first few of these types are the promoted integral
3785 // types; these types need to be first.
3786 // FIXME: What about complex?
3787 const unsigned FirstIntegralType = 0;
3788 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003789 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003790 LastPromotedIntegralType = 13;
3791 const unsigned FirstPromotedArithmeticType = 7,
3792 LastPromotedArithmeticType = 16;
3793 const unsigned NumArithmeticTypes = 16;
3794 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003795 Context.BoolTy, Context.CharTy, Context.WCharTy,
3796// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003797 Context.SignedCharTy, Context.ShortTy,
3798 Context.UnsignedCharTy, Context.UnsignedShortTy,
3799 Context.IntTy, Context.LongTy, Context.LongLongTy,
3800 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3801 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3802 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003803 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3804 "Invalid first promoted integral type");
3805 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3806 == Context.UnsignedLongLongTy &&
3807 "Invalid last promoted integral type");
3808 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3809 "Invalid first promoted arithmetic type");
3810 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3811 == Context.LongDoubleTy &&
3812 "Invalid last promoted arithmetic type");
3813
Douglas Gregora11693b2008-11-12 17:17:38 +00003814 // Find all of the types that the arguments can convert to, but only
3815 // if the operator we're looking at has built-in operator candidates
3816 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003817 Qualifiers VisibleTypeConversionsQuals;
3818 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003819 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3820 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3821
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003822 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003823 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3824 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003825 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003826 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003827 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003828 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003829 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003830 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003831 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003832 true,
3833 (Op == OO_Exclaim ||
3834 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003835 Op == OO_PipePipe),
3836 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003837 }
3838
3839 bool isComparison = false;
3840 switch (Op) {
3841 case OO_None:
3842 case NUM_OVERLOADED_OPERATORS:
3843 assert(false && "Expected an overloaded operator");
3844 break;
3845
Douglas Gregord08452f2008-11-19 15:42:04 +00003846 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003847 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003848 goto UnaryStar;
3849 else
3850 goto BinaryStar;
3851 break;
3852
3853 case OO_Plus: // '+' is either unary or binary
3854 if (NumArgs == 1)
3855 goto UnaryPlus;
3856 else
3857 goto BinaryPlus;
3858 break;
3859
3860 case OO_Minus: // '-' is either unary or binary
3861 if (NumArgs == 1)
3862 goto UnaryMinus;
3863 else
3864 goto BinaryMinus;
3865 break;
3866
3867 case OO_Amp: // '&' is either unary or binary
3868 if (NumArgs == 1)
3869 goto UnaryAmp;
3870 else
3871 goto BinaryAmp;
3872
3873 case OO_PlusPlus:
3874 case OO_MinusMinus:
3875 // C++ [over.built]p3:
3876 //
3877 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3878 // is either volatile or empty, there exist candidate operator
3879 // functions of the form
3880 //
3881 // VQ T& operator++(VQ T&);
3882 // T operator++(VQ T&, int);
3883 //
3884 // C++ [over.built]p4:
3885 //
3886 // For every pair (T, VQ), where T is an arithmetic type other
3887 // than bool, and VQ is either volatile or empty, there exist
3888 // candidate operator functions of the form
3889 //
3890 // VQ T& operator--(VQ T&);
3891 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003892 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003893 Arith < NumArithmeticTypes; ++Arith) {
3894 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003895 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003896 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003897
3898 // Non-volatile version.
3899 if (NumArgs == 1)
3900 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3901 else
3902 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003903 // heuristic to reduce number of builtin candidates in the set.
3904 // Add volatile version only if there are conversions to a volatile type.
3905 if (VisibleTypeConversionsQuals.hasVolatile()) {
3906 // Volatile version
3907 ParamTypes[0]
3908 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3909 if (NumArgs == 1)
3910 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3911 else
3912 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3913 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003914 }
3915
3916 // C++ [over.built]p5:
3917 //
3918 // For every pair (T, VQ), where T is a cv-qualified or
3919 // cv-unqualified object type, and VQ is either volatile or
3920 // empty, there exist candidate operator functions of the form
3921 //
3922 // T*VQ& operator++(T*VQ&);
3923 // T*VQ& operator--(T*VQ&);
3924 // T* operator++(T*VQ&, int);
3925 // T* operator--(T*VQ&, int);
3926 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3927 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3928 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003929 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003930 continue;
3931
Mike Stump11289f42009-09-09 15:08:12 +00003932 QualType ParamTypes[2] = {
3933 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003934 };
Mike Stump11289f42009-09-09 15:08:12 +00003935
Douglas Gregord08452f2008-11-19 15:42:04 +00003936 // Without volatile
3937 if (NumArgs == 1)
3938 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3939 else
3940 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3941
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003942 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3943 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003944 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003945 ParamTypes[0]
3946 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003947 if (NumArgs == 1)
3948 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3949 else
3950 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3951 }
3952 }
3953 break;
3954
3955 UnaryStar:
3956 // C++ [over.built]p6:
3957 // For every cv-qualified or cv-unqualified object type T, there
3958 // exist candidate operator functions of the form
3959 //
3960 // T& operator*(T*);
3961 //
3962 // C++ [over.built]p7:
3963 // For every function type T, there exist candidate operator
3964 // functions of the form
3965 // T& operator*(T*);
3966 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3967 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3968 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003969 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003970 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003971 &ParamTy, Args, 1, CandidateSet);
3972 }
3973 break;
3974
3975 UnaryPlus:
3976 // C++ [over.built]p8:
3977 // For every type T, there exist candidate operator functions of
3978 // the form
3979 //
3980 // T* operator+(T*);
3981 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3982 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3983 QualType ParamTy = *Ptr;
3984 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3985 }
Mike Stump11289f42009-09-09 15:08:12 +00003986
Douglas Gregord08452f2008-11-19 15:42:04 +00003987 // Fall through
3988
3989 UnaryMinus:
3990 // C++ [over.built]p9:
3991 // For every promoted arithmetic type T, there exist candidate
3992 // operator functions of the form
3993 //
3994 // T operator+(T);
3995 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003996 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003997 Arith < LastPromotedArithmeticType; ++Arith) {
3998 QualType ArithTy = ArithmeticTypes[Arith];
3999 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4000 }
4001 break;
4002
4003 case OO_Tilde:
4004 // C++ [over.built]p10:
4005 // For every promoted integral type T, there exist candidate
4006 // operator functions of the form
4007 //
4008 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004009 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004010 Int < LastPromotedIntegralType; ++Int) {
4011 QualType IntTy = ArithmeticTypes[Int];
4012 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4013 }
4014 break;
4015
Douglas Gregora11693b2008-11-12 17:17:38 +00004016 case OO_New:
4017 case OO_Delete:
4018 case OO_Array_New:
4019 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004020 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004021 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004022 break;
4023
4024 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004025 UnaryAmp:
4026 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004027 // C++ [over.match.oper]p3:
4028 // -- For the operator ',', the unary operator '&', or the
4029 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004030 break;
4031
Douglas Gregor84605ae2009-08-24 13:43:27 +00004032 case OO_EqualEqual:
4033 case OO_ExclaimEqual:
4034 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004035 // For every pointer to member type T, there exist candidate operator
4036 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004037 //
4038 // bool operator==(T,T);
4039 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004040 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004041 MemPtr = CandidateTypes.member_pointer_begin(),
4042 MemPtrEnd = CandidateTypes.member_pointer_end();
4043 MemPtr != MemPtrEnd;
4044 ++MemPtr) {
4045 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4046 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4047 }
Mike Stump11289f42009-09-09 15:08:12 +00004048
Douglas Gregor84605ae2009-08-24 13:43:27 +00004049 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004050
Douglas Gregora11693b2008-11-12 17:17:38 +00004051 case OO_Less:
4052 case OO_Greater:
4053 case OO_LessEqual:
4054 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004055 // C++ [over.built]p15:
4056 //
4057 // For every pointer or enumeration type T, there exist
4058 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004059 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004060 // bool operator<(T, T);
4061 // bool operator>(T, T);
4062 // bool operator<=(T, T);
4063 // bool operator>=(T, T);
4064 // bool operator==(T, T);
4065 // bool operator!=(T, T);
4066 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4067 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4068 QualType ParamTypes[2] = { *Ptr, *Ptr };
4069 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4070 }
Mike Stump11289f42009-09-09 15:08:12 +00004071 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004072 = CandidateTypes.enumeration_begin();
4073 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4074 QualType ParamTypes[2] = { *Enum, *Enum };
4075 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4076 }
4077
4078 // Fall through.
4079 isComparison = true;
4080
Douglas Gregord08452f2008-11-19 15:42:04 +00004081 BinaryPlus:
4082 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004083 if (!isComparison) {
4084 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4085
4086 // C++ [over.built]p13:
4087 //
4088 // For every cv-qualified or cv-unqualified object type T
4089 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004090 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004091 // T* operator+(T*, ptrdiff_t);
4092 // T& operator[](T*, ptrdiff_t); [BELOW]
4093 // T* operator-(T*, ptrdiff_t);
4094 // T* operator+(ptrdiff_t, T*);
4095 // T& operator[](ptrdiff_t, T*); [BELOW]
4096 //
4097 // C++ [over.built]p14:
4098 //
4099 // For every T, where T is a pointer to object type, there
4100 // exist candidate operator functions of the form
4101 //
4102 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004103 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004104 = CandidateTypes.pointer_begin();
4105 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4106 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4107
4108 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4109 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4110
4111 if (Op == OO_Plus) {
4112 // T* operator+(ptrdiff_t, T*);
4113 ParamTypes[0] = ParamTypes[1];
4114 ParamTypes[1] = *Ptr;
4115 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4116 } else {
4117 // ptrdiff_t operator-(T, T);
4118 ParamTypes[1] = *Ptr;
4119 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4120 Args, 2, CandidateSet);
4121 }
4122 }
4123 }
4124 // Fall through
4125
Douglas Gregora11693b2008-11-12 17:17:38 +00004126 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004127 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004128 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004129 // C++ [over.built]p12:
4130 //
4131 // For every pair of promoted arithmetic types L and R, there
4132 // exist candidate operator functions of the form
4133 //
4134 // LR operator*(L, R);
4135 // LR operator/(L, R);
4136 // LR operator+(L, R);
4137 // LR operator-(L, R);
4138 // bool operator<(L, R);
4139 // bool operator>(L, R);
4140 // bool operator<=(L, R);
4141 // bool operator>=(L, R);
4142 // bool operator==(L, R);
4143 // bool operator!=(L, R);
4144 //
4145 // where LR is the result of the usual arithmetic conversions
4146 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004147 //
4148 // C++ [over.built]p24:
4149 //
4150 // For every pair of promoted arithmetic types L and R, there exist
4151 // candidate operator functions of the form
4152 //
4153 // LR operator?(bool, L, R);
4154 //
4155 // where LR is the result of the usual arithmetic conversions
4156 // between types L and R.
4157 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004158 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004159 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004160 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004161 Right < LastPromotedArithmeticType; ++Right) {
4162 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004163 QualType Result
4164 = isComparison
4165 ? Context.BoolTy
4166 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004167 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4168 }
4169 }
4170 break;
4171
4172 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004173 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004174 case OO_Caret:
4175 case OO_Pipe:
4176 case OO_LessLess:
4177 case OO_GreaterGreater:
4178 // C++ [over.built]p17:
4179 //
4180 // For every pair of promoted integral types L and R, there
4181 // exist candidate operator functions of the form
4182 //
4183 // LR operator%(L, R);
4184 // LR operator&(L, R);
4185 // LR operator^(L, R);
4186 // LR operator|(L, R);
4187 // L operator<<(L, R);
4188 // L operator>>(L, R);
4189 //
4190 // where LR is the result of the usual arithmetic conversions
4191 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004192 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004193 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004194 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004195 Right < LastPromotedIntegralType; ++Right) {
4196 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4197 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4198 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004199 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004200 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4201 }
4202 }
4203 break;
4204
4205 case OO_Equal:
4206 // C++ [over.built]p20:
4207 //
4208 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004209 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004210 // empty, there exist candidate operator functions of the form
4211 //
4212 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004213 for (BuiltinCandidateTypeSet::iterator
4214 Enum = CandidateTypes.enumeration_begin(),
4215 EnumEnd = CandidateTypes.enumeration_end();
4216 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004217 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004218 CandidateSet);
4219 for (BuiltinCandidateTypeSet::iterator
4220 MemPtr = CandidateTypes.member_pointer_begin(),
4221 MemPtrEnd = CandidateTypes.member_pointer_end();
4222 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004223 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004224 CandidateSet);
4225 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004226
4227 case OO_PlusEqual:
4228 case OO_MinusEqual:
4229 // C++ [over.built]p19:
4230 //
4231 // For every pair (T, VQ), where T is any type and VQ is either
4232 // volatile or empty, there exist candidate operator functions
4233 // of the form
4234 //
4235 // T*VQ& operator=(T*VQ&, T*);
4236 //
4237 // C++ [over.built]p21:
4238 //
4239 // For every pair (T, VQ), where T is a cv-qualified or
4240 // cv-unqualified object type and VQ is either volatile or
4241 // empty, there exist candidate operator functions of the form
4242 //
4243 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4244 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4245 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4246 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4247 QualType ParamTypes[2];
4248 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4249
4250 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004251 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004252 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4253 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004254
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004255 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4256 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004257 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004258 ParamTypes[0]
4259 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004260 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4261 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004262 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004263 }
4264 // Fall through.
4265
4266 case OO_StarEqual:
4267 case OO_SlashEqual:
4268 // C++ [over.built]p18:
4269 //
4270 // For every triple (L, VQ, R), where L is an arithmetic type,
4271 // VQ is either volatile or empty, and R is a promoted
4272 // arithmetic type, there exist candidate operator functions of
4273 // the form
4274 //
4275 // VQ L& operator=(VQ L&, R);
4276 // VQ L& operator*=(VQ L&, R);
4277 // VQ L& operator/=(VQ L&, R);
4278 // VQ L& operator+=(VQ L&, R);
4279 // VQ L& operator-=(VQ L&, R);
4280 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004281 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004282 Right < LastPromotedArithmeticType; ++Right) {
4283 QualType ParamTypes[2];
4284 ParamTypes[1] = ArithmeticTypes[Right];
4285
4286 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004287 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004288 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4289 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004290
4291 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004292 if (VisibleTypeConversionsQuals.hasVolatile()) {
4293 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4294 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4295 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4296 /*IsAssigmentOperator=*/Op == OO_Equal);
4297 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004298 }
4299 }
4300 break;
4301
4302 case OO_PercentEqual:
4303 case OO_LessLessEqual:
4304 case OO_GreaterGreaterEqual:
4305 case OO_AmpEqual:
4306 case OO_CaretEqual:
4307 case OO_PipeEqual:
4308 // C++ [over.built]p22:
4309 //
4310 // For every triple (L, VQ, R), where L is an integral type, VQ
4311 // is either volatile or empty, and R is a promoted integral
4312 // type, there exist candidate operator functions of the form
4313 //
4314 // VQ L& operator%=(VQ L&, R);
4315 // VQ L& operator<<=(VQ L&, R);
4316 // VQ L& operator>>=(VQ L&, R);
4317 // VQ L& operator&=(VQ L&, R);
4318 // VQ L& operator^=(VQ L&, R);
4319 // VQ L& operator|=(VQ L&, R);
4320 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004321 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004322 Right < LastPromotedIntegralType; ++Right) {
4323 QualType ParamTypes[2];
4324 ParamTypes[1] = ArithmeticTypes[Right];
4325
4326 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004327 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004328 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004329 if (VisibleTypeConversionsQuals.hasVolatile()) {
4330 // Add this built-in operator as a candidate (VQ is 'volatile').
4331 ParamTypes[0] = ArithmeticTypes[Left];
4332 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4333 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4334 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4335 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004336 }
4337 }
4338 break;
4339
Douglas Gregord08452f2008-11-19 15:42:04 +00004340 case OO_Exclaim: {
4341 // C++ [over.operator]p23:
4342 //
4343 // There also exist candidate operator functions of the form
4344 //
Mike Stump11289f42009-09-09 15:08:12 +00004345 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004346 // bool operator&&(bool, bool); [BELOW]
4347 // bool operator||(bool, bool); [BELOW]
4348 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004349 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4350 /*IsAssignmentOperator=*/false,
4351 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004352 break;
4353 }
4354
Douglas Gregora11693b2008-11-12 17:17:38 +00004355 case OO_AmpAmp:
4356 case OO_PipePipe: {
4357 // C++ [over.operator]p23:
4358 //
4359 // There also exist candidate operator functions of the form
4360 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004361 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004362 // bool operator&&(bool, bool);
4363 // bool operator||(bool, bool);
4364 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004365 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4366 /*IsAssignmentOperator=*/false,
4367 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004368 break;
4369 }
4370
4371 case OO_Subscript:
4372 // C++ [over.built]p13:
4373 //
4374 // For every cv-qualified or cv-unqualified object type T there
4375 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004376 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004377 // T* operator+(T*, ptrdiff_t); [ABOVE]
4378 // T& operator[](T*, ptrdiff_t);
4379 // T* operator-(T*, ptrdiff_t); [ABOVE]
4380 // T* operator+(ptrdiff_t, T*); [ABOVE]
4381 // T& operator[](ptrdiff_t, T*);
4382 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4383 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4384 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004385 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004386 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004387
4388 // T& operator[](T*, ptrdiff_t)
4389 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4390
4391 // T& operator[](ptrdiff_t, T*);
4392 ParamTypes[0] = ParamTypes[1];
4393 ParamTypes[1] = *Ptr;
4394 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4395 }
4396 break;
4397
4398 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004399 // C++ [over.built]p11:
4400 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4401 // C1 is the same type as C2 or is a derived class of C2, T is an object
4402 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4403 // there exist candidate operator functions of the form
4404 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4405 // where CV12 is the union of CV1 and CV2.
4406 {
4407 for (BuiltinCandidateTypeSet::iterator Ptr =
4408 CandidateTypes.pointer_begin();
4409 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4410 QualType C1Ty = (*Ptr);
4411 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004412 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004413 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004414 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004415 if (!isa<RecordType>(C1))
4416 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004417 // heuristic to reduce number of builtin candidates in the set.
4418 // Add volatile/restrict version only if there are conversions to a
4419 // volatile/restrict type.
4420 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4421 continue;
4422 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4423 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004424 }
4425 for (BuiltinCandidateTypeSet::iterator
4426 MemPtr = CandidateTypes.member_pointer_begin(),
4427 MemPtrEnd = CandidateTypes.member_pointer_end();
4428 MemPtr != MemPtrEnd; ++MemPtr) {
4429 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4430 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004431 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004432 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4433 break;
4434 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4435 // build CV12 T&
4436 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004437 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4438 T.isVolatileQualified())
4439 continue;
4440 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4441 T.isRestrictQualified())
4442 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004443 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004444 QualType ResultTy = Context.getLValueReferenceType(T);
4445 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4446 }
4447 }
4448 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004449 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004450
4451 case OO_Conditional:
4452 // Note that we don't consider the first argument, since it has been
4453 // contextually converted to bool long ago. The candidates below are
4454 // therefore added as binary.
4455 //
4456 // C++ [over.built]p24:
4457 // For every type T, where T is a pointer or pointer-to-member type,
4458 // there exist candidate operator functions of the form
4459 //
4460 // T operator?(bool, T, T);
4461 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004462 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4463 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4464 QualType ParamTypes[2] = { *Ptr, *Ptr };
4465 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4466 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004467 for (BuiltinCandidateTypeSet::iterator Ptr =
4468 CandidateTypes.member_pointer_begin(),
4469 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4470 QualType ParamTypes[2] = { *Ptr, *Ptr };
4471 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4472 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004473 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004474 }
4475}
4476
Douglas Gregore254f902009-02-04 00:32:51 +00004477/// \brief Add function candidates found via argument-dependent lookup
4478/// to the set of overloading candidates.
4479///
4480/// This routine performs argument-dependent name lookup based on the
4481/// given function name (which may also be an operator name) and adds
4482/// all of the overload candidates found by ADL to the overload
4483/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004484void
Douglas Gregore254f902009-02-04 00:32:51 +00004485Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004486 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004487 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004488 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004489 OverloadCandidateSet& CandidateSet,
4490 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004491 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004492
John McCall91f61fc2010-01-26 06:04:06 +00004493 // FIXME: This approach for uniquing ADL results (and removing
4494 // redundant candidates from the set) relies on pointer-equality,
4495 // which means we need to key off the canonical decl. However,
4496 // always going back to the canonical decl might not get us the
4497 // right set of default arguments. What default arguments are
4498 // we supposed to consider on ADL candidates, anyway?
4499
Douglas Gregorcabea402009-09-22 15:41:20 +00004500 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004501 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004502
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004503 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004504 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4505 CandEnd = CandidateSet.end();
4506 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004507 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004508 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004509 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004510 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004511 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004512
4513 // For each of the ADL candidates we found, add it to the overload
4514 // set.
John McCall8fe68082010-01-26 07:16:45 +00004515 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004516 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004517 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004518 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004519 continue;
4520
John McCalla0296f72010-03-19 07:35:19 +00004521 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004522 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004523 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004524 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004525 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004526 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004527 }
Douglas Gregore254f902009-02-04 00:32:51 +00004528}
4529
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004530/// isBetterOverloadCandidate - Determines whether the first overload
4531/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004532bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004533Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004534 const OverloadCandidate& Cand2,
4535 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004536 // Define viable functions to be better candidates than non-viable
4537 // functions.
4538 if (!Cand2.Viable)
4539 return Cand1.Viable;
4540 else if (!Cand1.Viable)
4541 return false;
4542
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004543 // C++ [over.match.best]p1:
4544 //
4545 // -- if F is a static member function, ICS1(F) is defined such
4546 // that ICS1(F) is neither better nor worse than ICS1(G) for
4547 // any function G, and, symmetrically, ICS1(G) is neither
4548 // better nor worse than ICS1(F).
4549 unsigned StartArg = 0;
4550 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4551 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004552
Douglas Gregord3cb3562009-07-07 23:38:56 +00004553 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004554 // A viable function F1 is defined to be a better function than another
4555 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004556 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004557 unsigned NumArgs = Cand1.Conversions.size();
4558 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4559 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004560 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004561 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4562 Cand2.Conversions[ArgIdx])) {
4563 case ImplicitConversionSequence::Better:
4564 // Cand1 has a better conversion sequence.
4565 HasBetterConversion = true;
4566 break;
4567
4568 case ImplicitConversionSequence::Worse:
4569 // Cand1 can't be better than Cand2.
4570 return false;
4571
4572 case ImplicitConversionSequence::Indistinguishable:
4573 // Do nothing.
4574 break;
4575 }
4576 }
4577
Mike Stump11289f42009-09-09 15:08:12 +00004578 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004579 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004580 if (HasBetterConversion)
4581 return true;
4582
Mike Stump11289f42009-09-09 15:08:12 +00004583 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004584 // specialization, or, if not that,
4585 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4586 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4587 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004588
4589 // -- F1 and F2 are function template specializations, and the function
4590 // template for F1 is more specialized than the template for F2
4591 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004592 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004593 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4594 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004595 if (FunctionTemplateDecl *BetterTemplate
4596 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4597 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004598 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004599 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4600 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004601 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004602
Douglas Gregora1f013e2008-11-07 22:36:19 +00004603 // -- the context is an initialization by user-defined conversion
4604 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4605 // from the return type of F1 to the destination type (i.e.,
4606 // the type of the entity being initialized) is a better
4607 // conversion sequence than the standard conversion sequence
4608 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004609 if (Cand1.Function && Cand2.Function &&
4610 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004611 isa<CXXConversionDecl>(Cand2.Function)) {
4612 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4613 Cand2.FinalConversion)) {
4614 case ImplicitConversionSequence::Better:
4615 // Cand1 has a better conversion sequence.
4616 return true;
4617
4618 case ImplicitConversionSequence::Worse:
4619 // Cand1 can't be better than Cand2.
4620 return false;
4621
4622 case ImplicitConversionSequence::Indistinguishable:
4623 // Do nothing
4624 break;
4625 }
4626 }
4627
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004628 return false;
4629}
4630
Mike Stump11289f42009-09-09 15:08:12 +00004631/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004632/// within an overload candidate set.
4633///
4634/// \param CandidateSet the set of candidate functions.
4635///
4636/// \param Loc the location of the function name (or operator symbol) for
4637/// which overload resolution occurs.
4638///
Mike Stump11289f42009-09-09 15:08:12 +00004639/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004640/// function, Best points to the candidate function found.
4641///
4642/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004643OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4644 SourceLocation Loc,
4645 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004646 // Find the best viable function.
4647 Best = CandidateSet.end();
4648 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4649 Cand != CandidateSet.end(); ++Cand) {
4650 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004651 if (Best == CandidateSet.end() ||
4652 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004653 Best = Cand;
4654 }
4655 }
4656
4657 // If we didn't find any viable functions, abort.
4658 if (Best == CandidateSet.end())
4659 return OR_No_Viable_Function;
4660
4661 // Make sure that this function is better than every other viable
4662 // function. If not, we have an ambiguity.
4663 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4664 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004665 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004666 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004667 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004668 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004669 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004670 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004671 }
Mike Stump11289f42009-09-09 15:08:12 +00004672
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004673 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004674 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004675 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004676 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004677 return OR_Deleted;
4678
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004679 // C++ [basic.def.odr]p2:
4680 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004681 // when referred to from a potentially-evaluated expression. [Note: this
4682 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004683 // (clause 13), user-defined conversions (12.3.2), allocation function for
4684 // placement new (5.3.4), as well as non-default initialization (8.5).
4685 if (Best->Function)
4686 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004687 return OR_Success;
4688}
4689
John McCall53262c92010-01-12 02:15:36 +00004690namespace {
4691
4692enum OverloadCandidateKind {
4693 oc_function,
4694 oc_method,
4695 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004696 oc_function_template,
4697 oc_method_template,
4698 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004699 oc_implicit_default_constructor,
4700 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004701 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004702};
4703
John McCalle1ac8d12010-01-13 00:25:19 +00004704OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4705 FunctionDecl *Fn,
4706 std::string &Description) {
4707 bool isTemplate = false;
4708
4709 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4710 isTemplate = true;
4711 Description = S.getTemplateArgumentBindingsText(
4712 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4713 }
John McCallfd0b2f82010-01-06 09:43:14 +00004714
4715 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004716 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004717 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004718
John McCall53262c92010-01-12 02:15:36 +00004719 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4720 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004721 }
4722
4723 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4724 // This actually gets spelled 'candidate function' for now, but
4725 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004726 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004727 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004728
4729 assert(Meth->isCopyAssignment()
4730 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004731 return oc_implicit_copy_assignment;
4732 }
4733
John McCalle1ac8d12010-01-13 00:25:19 +00004734 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004735}
4736
4737} // end anonymous namespace
4738
4739// Notes the location of an overload candidate.
4740void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004741 std::string FnDesc;
4742 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4743 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4744 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004745}
4746
John McCall0d1da222010-01-12 00:44:57 +00004747/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4748/// "lead" diagnostic; it will be given two arguments, the source and
4749/// target types of the conversion.
4750void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4751 SourceLocation CaretLoc,
4752 const PartialDiagnostic &PDiag) {
4753 Diag(CaretLoc, PDiag)
4754 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4755 for (AmbiguousConversionSequence::const_iterator
4756 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4757 NoteOverloadCandidate(*I);
4758 }
John McCall12f97bc2010-01-08 04:41:39 +00004759}
4760
John McCall0d1da222010-01-12 00:44:57 +00004761namespace {
4762
John McCall6a61b522010-01-13 09:16:55 +00004763void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4764 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4765 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004766 assert(Cand->Function && "for now, candidate must be a function");
4767 FunctionDecl *Fn = Cand->Function;
4768
4769 // There's a conversion slot for the object argument if this is a
4770 // non-constructor method. Note that 'I' corresponds the
4771 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004772 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004773 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004774 if (I == 0)
4775 isObjectArgument = true;
4776 else
4777 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004778 }
4779
John McCalle1ac8d12010-01-13 00:25:19 +00004780 std::string FnDesc;
4781 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4782
John McCall6a61b522010-01-13 09:16:55 +00004783 Expr *FromExpr = Conv.Bad.FromExpr;
4784 QualType FromTy = Conv.Bad.getFromType();
4785 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004786
John McCallfb7ad0f2010-02-02 02:42:52 +00004787 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004788 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004789 Expr *E = FromExpr->IgnoreParens();
4790 if (isa<UnaryOperator>(E))
4791 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004792 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004793
4794 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4795 << (unsigned) FnKind << FnDesc
4796 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4797 << ToTy << Name << I+1;
4798 return;
4799 }
4800
John McCall6d174642010-01-23 08:10:49 +00004801 // Do some hand-waving analysis to see if the non-viability is due
4802 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004803 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4804 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4805 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4806 CToTy = RT->getPointeeType();
4807 else {
4808 // TODO: detect and diagnose the full richness of const mismatches.
4809 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4810 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4811 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4812 }
4813
4814 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4815 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4816 // It is dumb that we have to do this here.
4817 while (isa<ArrayType>(CFromTy))
4818 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4819 while (isa<ArrayType>(CToTy))
4820 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4821
4822 Qualifiers FromQs = CFromTy.getQualifiers();
4823 Qualifiers ToQs = CToTy.getQualifiers();
4824
4825 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4826 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4827 << (unsigned) FnKind << FnDesc
4828 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4829 << FromTy
4830 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4831 << (unsigned) isObjectArgument << I+1;
4832 return;
4833 }
4834
4835 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4836 assert(CVR && "unexpected qualifiers mismatch");
4837
4838 if (isObjectArgument) {
4839 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4840 << (unsigned) FnKind << FnDesc
4841 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4842 << FromTy << (CVR - 1);
4843 } else {
4844 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4845 << (unsigned) FnKind << FnDesc
4846 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4847 << FromTy << (CVR - 1) << I+1;
4848 }
4849 return;
4850 }
4851
John McCall6d174642010-01-23 08:10:49 +00004852 // Diagnose references or pointers to incomplete types differently,
4853 // since it's far from impossible that the incompleteness triggered
4854 // the failure.
4855 QualType TempFromTy = FromTy.getNonReferenceType();
4856 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4857 TempFromTy = PTy->getPointeeType();
4858 if (TempFromTy->isIncompleteType()) {
4859 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4860 << (unsigned) FnKind << FnDesc
4861 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4862 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4863 return;
4864 }
4865
John McCall47000992010-01-14 03:28:57 +00004866 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004867 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4868 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004869 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004870 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004871}
4872
4873void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4874 unsigned NumFormalArgs) {
4875 // TODO: treat calls to a missing default constructor as a special case
4876
4877 FunctionDecl *Fn = Cand->Function;
4878 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4879
4880 unsigned MinParams = Fn->getMinRequiredArguments();
4881
4882 // at least / at most / exactly
4883 unsigned mode, modeCount;
4884 if (NumFormalArgs < MinParams) {
4885 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4886 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4887 mode = 0; // "at least"
4888 else
4889 mode = 2; // "exactly"
4890 modeCount = MinParams;
4891 } else {
4892 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4893 if (MinParams != FnTy->getNumArgs())
4894 mode = 1; // "at most"
4895 else
4896 mode = 2; // "exactly"
4897 modeCount = FnTy->getNumArgs();
4898 }
4899
4900 std::string Description;
4901 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4902
4903 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4904 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004905}
4906
John McCall8b9ed552010-02-01 18:53:26 +00004907/// Diagnose a failed template-argument deduction.
4908void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4909 Expr **Args, unsigned NumArgs) {
4910 FunctionDecl *Fn = Cand->Function; // pattern
4911
4912 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4913 Cand->DeductionFailure.TemplateParameter);
4914
4915 switch (Cand->DeductionFailure.Result) {
4916 case Sema::TDK_Success:
4917 llvm_unreachable("TDK_success while diagnosing bad deduction");
4918
4919 case Sema::TDK_Incomplete: {
4920 NamedDecl *ParamD;
4921 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4922 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4923 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4924 assert(ParamD && "no parameter found for incomplete deduction result");
4925 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4926 << ParamD->getDeclName();
4927 return;
4928 }
4929
4930 // TODO: diagnose these individually, then kill off
4931 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4932 case Sema::TDK_InstantiationDepth:
4933 case Sema::TDK_Inconsistent:
4934 case Sema::TDK_InconsistentQuals:
4935 case Sema::TDK_SubstitutionFailure:
4936 case Sema::TDK_NonDeducedMismatch:
4937 case Sema::TDK_TooManyArguments:
4938 case Sema::TDK_TooFewArguments:
4939 case Sema::TDK_InvalidExplicitArguments:
4940 case Sema::TDK_FailedOverloadResolution:
4941 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4942 return;
4943 }
4944}
4945
4946/// Generates a 'note' diagnostic for an overload candidate. We've
4947/// already generated a primary error at the call site.
4948///
4949/// It really does need to be a single diagnostic with its caret
4950/// pointed at the candidate declaration. Yes, this creates some
4951/// major challenges of technical writing. Yes, this makes pointing
4952/// out problems with specific arguments quite awkward. It's still
4953/// better than generating twenty screens of text for every failed
4954/// overload.
4955///
4956/// It would be great to be able to express per-candidate problems
4957/// more richly for those diagnostic clients that cared, but we'd
4958/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004959void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4960 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004961 FunctionDecl *Fn = Cand->Function;
4962
John McCall12f97bc2010-01-08 04:41:39 +00004963 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004964 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004965 std::string FnDesc;
4966 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004967
4968 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004969 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004970 return;
John McCall12f97bc2010-01-08 04:41:39 +00004971 }
4972
John McCalle1ac8d12010-01-13 00:25:19 +00004973 // We don't really have anything else to say about viable candidates.
4974 if (Cand->Viable) {
4975 S.NoteOverloadCandidate(Fn);
4976 return;
4977 }
John McCall0d1da222010-01-12 00:44:57 +00004978
John McCall6a61b522010-01-13 09:16:55 +00004979 switch (Cand->FailureKind) {
4980 case ovl_fail_too_many_arguments:
4981 case ovl_fail_too_few_arguments:
4982 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004983
John McCall6a61b522010-01-13 09:16:55 +00004984 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004985 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4986
John McCallfe796dd2010-01-23 05:17:32 +00004987 case ovl_fail_trivial_conversion:
4988 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004989 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00004990 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004991
John McCall65eb8792010-02-25 01:37:24 +00004992 case ovl_fail_bad_conversion: {
4993 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4994 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00004995 if (Cand->Conversions[I].isBad())
4996 return DiagnoseBadConversion(S, Cand, I);
4997
4998 // FIXME: this currently happens when we're called from SemaInit
4999 // when user-conversion overload fails. Figure out how to handle
5000 // those conditions and diagnose them well.
5001 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005002 }
John McCall65eb8792010-02-25 01:37:24 +00005003 }
John McCalld3224162010-01-08 00:58:21 +00005004}
5005
5006void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5007 // Desugar the type of the surrogate down to a function type,
5008 // retaining as many typedefs as possible while still showing
5009 // the function type (and, therefore, its parameter types).
5010 QualType FnType = Cand->Surrogate->getConversionType();
5011 bool isLValueReference = false;
5012 bool isRValueReference = false;
5013 bool isPointer = false;
5014 if (const LValueReferenceType *FnTypeRef =
5015 FnType->getAs<LValueReferenceType>()) {
5016 FnType = FnTypeRef->getPointeeType();
5017 isLValueReference = true;
5018 } else if (const RValueReferenceType *FnTypeRef =
5019 FnType->getAs<RValueReferenceType>()) {
5020 FnType = FnTypeRef->getPointeeType();
5021 isRValueReference = true;
5022 }
5023 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5024 FnType = FnTypePtr->getPointeeType();
5025 isPointer = true;
5026 }
5027 // Desugar down to a function type.
5028 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5029 // Reconstruct the pointer/reference as appropriate.
5030 if (isPointer) FnType = S.Context.getPointerType(FnType);
5031 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5032 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5033
5034 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5035 << FnType;
5036}
5037
5038void NoteBuiltinOperatorCandidate(Sema &S,
5039 const char *Opc,
5040 SourceLocation OpLoc,
5041 OverloadCandidate *Cand) {
5042 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5043 std::string TypeStr("operator");
5044 TypeStr += Opc;
5045 TypeStr += "(";
5046 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5047 if (Cand->Conversions.size() == 1) {
5048 TypeStr += ")";
5049 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5050 } else {
5051 TypeStr += ", ";
5052 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5053 TypeStr += ")";
5054 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5055 }
5056}
5057
5058void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5059 OverloadCandidate *Cand) {
5060 unsigned NoOperands = Cand->Conversions.size();
5061 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5062 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005063 if (ICS.isBad()) break; // all meaningless after first invalid
5064 if (!ICS.isAmbiguous()) continue;
5065
5066 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005067 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005068 }
5069}
5070
John McCall3712d9e2010-01-15 23:32:50 +00005071SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5072 if (Cand->Function)
5073 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005074 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005075 return Cand->Surrogate->getLocation();
5076 return SourceLocation();
5077}
5078
John McCallad2587a2010-01-12 00:48:53 +00005079struct CompareOverloadCandidatesForDisplay {
5080 Sema &S;
5081 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005082
5083 bool operator()(const OverloadCandidate *L,
5084 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005085 // Fast-path this check.
5086 if (L == R) return false;
5087
John McCall12f97bc2010-01-08 04:41:39 +00005088 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005089 if (L->Viable) {
5090 if (!R->Viable) return true;
5091
5092 // TODO: introduce a tri-valued comparison for overload
5093 // candidates. Would be more worthwhile if we had a sort
5094 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005095 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5096 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005097 } else if (R->Viable)
5098 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005099
John McCall3712d9e2010-01-15 23:32:50 +00005100 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005101
John McCall3712d9e2010-01-15 23:32:50 +00005102 // Criteria by which we can sort non-viable candidates:
5103 if (!L->Viable) {
5104 // 1. Arity mismatches come after other candidates.
5105 if (L->FailureKind == ovl_fail_too_many_arguments ||
5106 L->FailureKind == ovl_fail_too_few_arguments)
5107 return false;
5108 if (R->FailureKind == ovl_fail_too_many_arguments ||
5109 R->FailureKind == ovl_fail_too_few_arguments)
5110 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005111
John McCallfe796dd2010-01-23 05:17:32 +00005112 // 2. Bad conversions come first and are ordered by the number
5113 // of bad conversions and quality of good conversions.
5114 if (L->FailureKind == ovl_fail_bad_conversion) {
5115 if (R->FailureKind != ovl_fail_bad_conversion)
5116 return true;
5117
5118 // If there's any ordering between the defined conversions...
5119 // FIXME: this might not be transitive.
5120 assert(L->Conversions.size() == R->Conversions.size());
5121
5122 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005123 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5124 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005125 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5126 R->Conversions[I])) {
5127 case ImplicitConversionSequence::Better:
5128 leftBetter++;
5129 break;
5130
5131 case ImplicitConversionSequence::Worse:
5132 leftBetter--;
5133 break;
5134
5135 case ImplicitConversionSequence::Indistinguishable:
5136 break;
5137 }
5138 }
5139 if (leftBetter > 0) return true;
5140 if (leftBetter < 0) return false;
5141
5142 } else if (R->FailureKind == ovl_fail_bad_conversion)
5143 return false;
5144
John McCall3712d9e2010-01-15 23:32:50 +00005145 // TODO: others?
5146 }
5147
5148 // Sort everything else by location.
5149 SourceLocation LLoc = GetLocationForCandidate(L);
5150 SourceLocation RLoc = GetLocationForCandidate(R);
5151
5152 // Put candidates without locations (e.g. builtins) at the end.
5153 if (LLoc.isInvalid()) return false;
5154 if (RLoc.isInvalid()) return true;
5155
5156 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005157 }
5158};
5159
John McCallfe796dd2010-01-23 05:17:32 +00005160/// CompleteNonViableCandidate - Normally, overload resolution only
5161/// computes up to the first
5162void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5163 Expr **Args, unsigned NumArgs) {
5164 assert(!Cand->Viable);
5165
5166 // Don't do anything on failures other than bad conversion.
5167 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5168
5169 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005170 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005171 unsigned ConvCount = Cand->Conversions.size();
5172 while (true) {
5173 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5174 ConvIdx++;
5175 if (Cand->Conversions[ConvIdx - 1].isBad())
5176 break;
5177 }
5178
5179 if (ConvIdx == ConvCount)
5180 return;
5181
John McCall65eb8792010-02-25 01:37:24 +00005182 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5183 "remaining conversion is initialized?");
5184
Douglas Gregoradc7a702010-04-16 17:45:54 +00005185 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005186 // operation somehow.
5187 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005188
5189 const FunctionProtoType* Proto;
5190 unsigned ArgIdx = ConvIdx;
5191
5192 if (Cand->IsSurrogate) {
5193 QualType ConvType
5194 = Cand->Surrogate->getConversionType().getNonReferenceType();
5195 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5196 ConvType = ConvPtrType->getPointeeType();
5197 Proto = ConvType->getAs<FunctionProtoType>();
5198 ArgIdx--;
5199 } else if (Cand->Function) {
5200 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5201 if (isa<CXXMethodDecl>(Cand->Function) &&
5202 !isa<CXXConstructorDecl>(Cand->Function))
5203 ArgIdx--;
5204 } else {
5205 // Builtin binary operator with a bad first conversion.
5206 assert(ConvCount <= 3);
5207 for (; ConvIdx != ConvCount; ++ConvIdx)
5208 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005209 = TryCopyInitialization(S, Args[ConvIdx],
5210 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5211 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005212 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005213 return;
5214 }
5215
5216 // Fill in the rest of the conversions.
5217 unsigned NumArgsInProto = Proto->getNumArgs();
5218 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5219 if (ArgIdx < NumArgsInProto)
5220 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005221 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5222 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005223 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005224 else
5225 Cand->Conversions[ConvIdx].setEllipsis();
5226 }
5227}
5228
John McCalld3224162010-01-08 00:58:21 +00005229} // end anonymous namespace
5230
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005231/// PrintOverloadCandidates - When overload resolution fails, prints
5232/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005233/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005234void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005235Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005236 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005237 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005238 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005239 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005240 // Sort the candidates by viability and position. Sorting directly would
5241 // be prohibitive, so we make a set of pointers and sort those.
5242 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5243 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5244 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5245 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005246 Cand != LastCand; ++Cand) {
5247 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005248 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005249 else if (OCD == OCD_AllCandidates) {
5250 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5251 Cands.push_back(Cand);
5252 }
5253 }
5254
John McCallad2587a2010-01-12 00:48:53 +00005255 std::sort(Cands.begin(), Cands.end(),
5256 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005257
John McCall0d1da222010-01-12 00:44:57 +00005258 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005259
John McCall12f97bc2010-01-08 04:41:39 +00005260 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5261 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5262 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005263
John McCalld3224162010-01-08 00:58:21 +00005264 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005265 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005266 else if (Cand->IsSurrogate)
5267 NoteSurrogateCandidate(*this, Cand);
5268
5269 // This a builtin candidate. We do not, in general, want to list
5270 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005271 else if (Cand->Viable) {
5272 // Generally we only see ambiguities including viable builtin
5273 // operators if overload resolution got screwed up by an
5274 // ambiguous user-defined conversion.
5275 //
5276 // FIXME: It's quite possible for different conversions to see
5277 // different ambiguities, though.
5278 if (!ReportedAmbiguousConversions) {
5279 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5280 ReportedAmbiguousConversions = true;
5281 }
John McCalld3224162010-01-08 00:58:21 +00005282
John McCall0d1da222010-01-12 00:44:57 +00005283 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005284 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005285 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005286 }
5287}
5288
John McCalla0296f72010-03-19 07:35:19 +00005289static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005290 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005291 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005292
John McCalla0296f72010-03-19 07:35:19 +00005293 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005294}
5295
Douglas Gregorcd695e52008-11-10 20:40:00 +00005296/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5297/// an overloaded function (C++ [over.over]), where @p From is an
5298/// expression with overloaded function type and @p ToType is the type
5299/// we're trying to resolve to. For example:
5300///
5301/// @code
5302/// int f(double);
5303/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005304///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005305/// int (*pfd)(double) = f; // selects f(double)
5306/// @endcode
5307///
5308/// This routine returns the resulting FunctionDecl if it could be
5309/// resolved, and NULL otherwise. When @p Complain is true, this
5310/// routine will emit diagnostics if there is an error.
5311FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005312Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005313 bool Complain,
5314 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005315 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005316 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005317 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005318 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005319 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005320 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005321 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005322 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005323 FunctionType = MemTypePtr->getPointeeType();
5324 IsMember = true;
5325 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005326
Douglas Gregorcd695e52008-11-10 20:40:00 +00005327 // C++ [over.over]p1:
5328 // [...] [Note: any redundant set of parentheses surrounding the
5329 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005330 // C++ [over.over]p1:
5331 // [...] The overloaded function name can be preceded by the &
5332 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005333 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5334 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5335 if (OvlExpr->hasExplicitTemplateArgs()) {
5336 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5337 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005338 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005339
5340 // We expect a pointer or reference to function, or a function pointer.
5341 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5342 if (!FunctionType->isFunctionType()) {
5343 if (Complain)
5344 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5345 << OvlExpr->getName() << ToType;
5346
5347 return 0;
5348 }
5349
5350 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005351
Douglas Gregorcd695e52008-11-10 20:40:00 +00005352 // Look through all of the overloaded functions, searching for one
5353 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005354 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005355 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5356
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005357 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005358 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5359 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005360 // Look through any using declarations to find the underlying function.
5361 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5362
Douglas Gregorcd695e52008-11-10 20:40:00 +00005363 // C++ [over.over]p3:
5364 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005365 // targets of type "pointer-to-function" or "reference-to-function."
5366 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005367 // type "pointer-to-member-function."
5368 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005369
Mike Stump11289f42009-09-09 15:08:12 +00005370 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005371 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005372 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005373 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005374 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005375 // static when converting to member pointer.
5376 if (Method->isStatic() == IsMember)
5377 continue;
5378 } else if (IsMember)
5379 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005380
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005381 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005382 // If the name is a function template, template argument deduction is
5383 // done (14.8.2.2), and if the argument deduction succeeds, the
5384 // resulting template argument list is used to generate a single
5385 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005386 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005387 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005388 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005389 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005390 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005391 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005392 FunctionType, Specialization, Info)) {
5393 // FIXME: make a note of the failed deduction for diagnostics.
5394 (void)Result;
5395 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005396 // FIXME: If the match isn't exact, shouldn't we just drop this as
5397 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005398 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005399 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005400 Matches.push_back(std::make_pair(I.getPair(),
5401 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005402 }
John McCalld14a8642009-11-21 08:51:07 +00005403
5404 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005405 }
Mike Stump11289f42009-09-09 15:08:12 +00005406
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005407 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005408 // Skip non-static functions when converting to pointer, and static
5409 // when converting to member pointer.
5410 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005411 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005412
5413 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005414 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005415 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005416 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005417 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005418
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005419 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005420 QualType ResultTy;
5421 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5422 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5423 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005424 Matches.push_back(std::make_pair(I.getPair(),
5425 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005426 FoundNonTemplateFunction = true;
5427 }
Mike Stump11289f42009-09-09 15:08:12 +00005428 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005429 }
5430
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005431 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005432 if (Matches.empty()) {
5433 if (Complain) {
5434 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5435 << OvlExpr->getName() << FunctionType;
5436 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5437 E = OvlExpr->decls_end();
5438 I != E; ++I)
5439 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5440 NoteOverloadCandidate(F);
5441 }
5442
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005443 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005444 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005445 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005446 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005447 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005448 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005449 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005450 return Result;
5451 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005452
5453 // C++ [over.over]p4:
5454 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005455 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005456 // [...] and any given function template specialization F1 is
5457 // eliminated if the set contains a second function template
5458 // specialization whose function template is more specialized
5459 // than the function template of F1 according to the partial
5460 // ordering rules of 14.5.5.2.
5461
5462 // The algorithm specified above is quadratic. We instead use a
5463 // two-pass algorithm (similar to the one used to identify the
5464 // best viable function in an overload set) that identifies the
5465 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005466
5467 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5468 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5469 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005470
5471 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005472 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005473 TPOC_Other, From->getLocStart(),
5474 PDiag(),
5475 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005476 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005477 PDiag(diag::note_ovl_candidate)
5478 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005479 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005480 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005481 FoundResult = Matches[Result - MatchesCopy.begin()].first;
5482 if (Complain)
5483 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00005484 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005485 }
Mike Stump11289f42009-09-09 15:08:12 +00005486
Douglas Gregorfae1d712009-09-26 03:56:17 +00005487 // [...] any function template specializations in the set are
5488 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005489 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005490 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005491 ++I;
5492 else {
John McCalla0296f72010-03-19 07:35:19 +00005493 Matches[I] = Matches[--N];
5494 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005495 }
5496 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005497
Mike Stump11289f42009-09-09 15:08:12 +00005498 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005499 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005500 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005501 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005502 FoundResult = Matches[0].first;
John McCall58cc69d2010-01-27 01:50:18 +00005503 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00005504 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5505 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005506 }
Mike Stump11289f42009-09-09 15:08:12 +00005507
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005508 // FIXME: We should probably return the same thing that BestViableFunction
5509 // returns (even if we issue the diagnostics here).
5510 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005511 << Matches[0].second->getDeclName();
5512 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5513 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005514 return 0;
5515}
5516
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005517/// \brief Given an expression that refers to an overloaded function, try to
5518/// resolve that overloaded function expression down to a single function.
5519///
5520/// This routine can only resolve template-ids that refer to a single function
5521/// template, where that template-id refers to a single template whose template
5522/// arguments are either provided by the template-id or have defaults,
5523/// as described in C++0x [temp.arg.explicit]p3.
5524FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5525 // C++ [over.over]p1:
5526 // [...] [Note: any redundant set of parentheses surrounding the
5527 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005528 // C++ [over.over]p1:
5529 // [...] The overloaded function name can be preceded by the &
5530 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005531
5532 if (From->getType() != Context.OverloadTy)
5533 return 0;
5534
5535 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005536
5537 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005538 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005539 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005540
5541 TemplateArgumentListInfo ExplicitTemplateArgs;
5542 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005543
5544 // Look through all of the overloaded functions, searching for one
5545 // whose type matches exactly.
5546 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005547 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5548 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005549 // C++0x [temp.arg.explicit]p3:
5550 // [...] In contexts where deduction is done and fails, or in contexts
5551 // where deduction is not done, if a template argument list is
5552 // specified and it, along with any default template arguments,
5553 // identifies a single function template specialization, then the
5554 // template-id is an lvalue for the function template specialization.
5555 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5556
5557 // C++ [over.over]p2:
5558 // If the name is a function template, template argument deduction is
5559 // done (14.8.2.2), and if the argument deduction succeeds, the
5560 // resulting template argument list is used to generate a single
5561 // function template specialization, which is added to the set of
5562 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005563 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005564 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005565 if (TemplateDeductionResult Result
5566 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5567 Specialization, Info)) {
5568 // FIXME: make a note of the failed deduction for diagnostics.
5569 (void)Result;
5570 continue;
5571 }
5572
5573 // Multiple matches; we can't resolve to a single declaration.
5574 if (Matched)
5575 return 0;
5576
5577 Matched = Specialization;
5578 }
5579
5580 return Matched;
5581}
5582
Douglas Gregorcabea402009-09-22 15:41:20 +00005583/// \brief Add a single candidate to the overload set.
5584static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005585 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005586 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005587 Expr **Args, unsigned NumArgs,
5588 OverloadCandidateSet &CandidateSet,
5589 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005590 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005591 if (isa<UsingShadowDecl>(Callee))
5592 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5593
Douglas Gregorcabea402009-09-22 15:41:20 +00005594 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005595 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005596 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005597 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005598 return;
John McCalld14a8642009-11-21 08:51:07 +00005599 }
5600
5601 if (FunctionTemplateDecl *FuncTemplate
5602 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005603 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5604 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005605 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005606 return;
5607 }
5608
5609 assert(false && "unhandled case in overloaded call candidate");
5610
5611 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005612}
5613
5614/// \brief Add the overload candidates named by callee and/or found by argument
5615/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005616void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005617 Expr **Args, unsigned NumArgs,
5618 OverloadCandidateSet &CandidateSet,
5619 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005620
5621#ifndef NDEBUG
5622 // Verify that ArgumentDependentLookup is consistent with the rules
5623 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005624 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005625 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5626 // and let Y be the lookup set produced by argument dependent
5627 // lookup (defined as follows). If X contains
5628 //
5629 // -- a declaration of a class member, or
5630 //
5631 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005632 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005633 //
5634 // -- a declaration that is neither a function or a function
5635 // template
5636 //
5637 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005638
John McCall57500772009-12-16 12:17:52 +00005639 if (ULE->requiresADL()) {
5640 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5641 E = ULE->decls_end(); I != E; ++I) {
5642 assert(!(*I)->getDeclContext()->isRecord());
5643 assert(isa<UsingShadowDecl>(*I) ||
5644 !(*I)->getDeclContext()->isFunctionOrMethod());
5645 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005646 }
5647 }
5648#endif
5649
John McCall57500772009-12-16 12:17:52 +00005650 // It would be nice to avoid this copy.
5651 TemplateArgumentListInfo TABuffer;
5652 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5653 if (ULE->hasExplicitTemplateArgs()) {
5654 ULE->copyTemplateArgumentsInto(TABuffer);
5655 ExplicitTemplateArgs = &TABuffer;
5656 }
5657
5658 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5659 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005660 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005661 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005662 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005663
John McCall57500772009-12-16 12:17:52 +00005664 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005665 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5666 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005667 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005668 CandidateSet,
5669 PartialOverloading);
5670}
John McCalld681c392009-12-16 08:11:27 +00005671
John McCall57500772009-12-16 12:17:52 +00005672static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5673 Expr **Args, unsigned NumArgs) {
5674 Fn->Destroy(SemaRef.Context);
5675 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5676 Args[Arg]->Destroy(SemaRef.Context);
5677 return SemaRef.ExprError();
5678}
5679
John McCalld681c392009-12-16 08:11:27 +00005680/// Attempts to recover from a call where no functions were found.
5681///
5682/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005683static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005684BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005685 UnresolvedLookupExpr *ULE,
5686 SourceLocation LParenLoc,
5687 Expr **Args, unsigned NumArgs,
5688 SourceLocation *CommaLocs,
5689 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005690
5691 CXXScopeSpec SS;
5692 if (ULE->getQualifier()) {
5693 SS.setScopeRep(ULE->getQualifier());
5694 SS.setRange(ULE->getQualifierRange());
5695 }
5696
John McCall57500772009-12-16 12:17:52 +00005697 TemplateArgumentListInfo TABuffer;
5698 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5699 if (ULE->hasExplicitTemplateArgs()) {
5700 ULE->copyTemplateArgumentsInto(TABuffer);
5701 ExplicitTemplateArgs = &TABuffer;
5702 }
5703
John McCalld681c392009-12-16 08:11:27 +00005704 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5705 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005706 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005707 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005708
John McCall57500772009-12-16 12:17:52 +00005709 assert(!R.empty() && "lookup results empty despite recovery");
5710
5711 // Build an implicit member call if appropriate. Just drop the
5712 // casts and such from the call, we don't really care.
5713 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5714 if ((*R.begin())->isCXXClassMember())
5715 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5716 else if (ExplicitTemplateArgs)
5717 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5718 else
5719 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5720
5721 if (NewFn.isInvalid())
5722 return Destroy(SemaRef, Fn, Args, NumArgs);
5723
5724 Fn->Destroy(SemaRef.Context);
5725
5726 // This shouldn't cause an infinite loop because we're giving it
5727 // an expression with non-empty lookup results, which should never
5728 // end up here.
5729 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5730 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5731 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005732}
Douglas Gregorcabea402009-09-22 15:41:20 +00005733
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005734/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005735/// (which eventually refers to the declaration Func) and the call
5736/// arguments Args/NumArgs, attempt to resolve the function call down
5737/// to a specific function. If overload resolution succeeds, returns
5738/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005739/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005740/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005741Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005742Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005743 SourceLocation LParenLoc,
5744 Expr **Args, unsigned NumArgs,
5745 SourceLocation *CommaLocs,
5746 SourceLocation RParenLoc) {
5747#ifndef NDEBUG
5748 if (ULE->requiresADL()) {
5749 // To do ADL, we must have found an unqualified name.
5750 assert(!ULE->getQualifier() && "qualified name with ADL");
5751
5752 // We don't perform ADL for implicit declarations of builtins.
5753 // Verify that this was correctly set up.
5754 FunctionDecl *F;
5755 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5756 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5757 F->getBuiltinID() && F->isImplicit())
5758 assert(0 && "performing ADL for builtin");
5759
5760 // We don't perform ADL in C.
5761 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5762 }
5763#endif
5764
John McCallbc077cf2010-02-08 23:07:23 +00005765 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005766
John McCall57500772009-12-16 12:17:52 +00005767 // Add the functions denoted by the callee to the set of candidate
5768 // functions, including those from argument-dependent lookup.
5769 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005770
5771 // If we found nothing, try to recover.
5772 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5773 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005774 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005775 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00005776 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005777
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005778 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005779 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005780 case OR_Success: {
5781 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00005782 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall16df1e52010-03-30 21:47:33 +00005783 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00005784 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5785 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005786
5787 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005788 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005789 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005790 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005791 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005792 break;
5793
5794 case OR_Ambiguous:
5795 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005796 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005797 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005798 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005799
5800 case OR_Deleted:
5801 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5802 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005803 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005804 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005805 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005806 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005807 }
5808
5809 // Overload resolution failed. Destroy all of the subexpressions and
5810 // return NULL.
5811 Fn->Destroy(Context);
5812 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5813 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005814 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005815}
5816
John McCall4c4c1df2010-01-26 03:27:55 +00005817static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005818 return Functions.size() > 1 ||
5819 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5820}
5821
Douglas Gregor084d8552009-03-13 23:49:33 +00005822/// \brief Create a unary operation that may resolve to an overloaded
5823/// operator.
5824///
5825/// \param OpLoc The location of the operator itself (e.g., '*').
5826///
5827/// \param OpcIn The UnaryOperator::Opcode that describes this
5828/// operator.
5829///
5830/// \param Functions The set of non-member functions that will be
5831/// considered by overload resolution. The caller needs to build this
5832/// set based on the context using, e.g.,
5833/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5834/// set should not contain any member functions; those will be added
5835/// by CreateOverloadedUnaryOp().
5836///
5837/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005838Sema::OwningExprResult
5839Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5840 const UnresolvedSetImpl &Fns,
5841 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005842 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5843 Expr *Input = (Expr *)input.get();
5844
5845 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5846 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5847 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5848
5849 Expr *Args[2] = { Input, 0 };
5850 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005851
Douglas Gregor084d8552009-03-13 23:49:33 +00005852 // For post-increment and post-decrement, add the implicit '0' as
5853 // the second argument, so that we know this is a post-increment or
5854 // post-decrement.
5855 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5856 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005857 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005858 SourceLocation());
5859 NumArgs = 2;
5860 }
5861
5862 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005863 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005864 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005865 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005866 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005867 /*ADL*/ true, IsOverloaded(Fns));
5868 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005869
Douglas Gregor084d8552009-03-13 23:49:33 +00005870 input.release();
5871 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5872 &Args[0], NumArgs,
5873 Context.DependentTy,
5874 OpLoc));
5875 }
5876
5877 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005878 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005879
5880 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005881 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005882
5883 // Add operator candidates that are member functions.
5884 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5885
John McCall4c4c1df2010-01-26 03:27:55 +00005886 // Add candidates from ADL.
5887 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005888 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005889 /*ExplicitTemplateArgs*/ 0,
5890 CandidateSet);
5891
Douglas Gregor084d8552009-03-13 23:49:33 +00005892 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005893 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005894
5895 // Perform overload resolution.
5896 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005897 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005898 case OR_Success: {
5899 // We found a built-in operator or an overloaded operator.
5900 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005901
Douglas Gregor084d8552009-03-13 23:49:33 +00005902 if (FnDecl) {
5903 // We matched an overloaded operator. Build a call to that
5904 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005905
Douglas Gregor084d8552009-03-13 23:49:33 +00005906 // Convert the arguments.
5907 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00005908 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00005909
John McCall16df1e52010-03-30 21:47:33 +00005910 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5911 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005912 return ExprError();
5913 } else {
5914 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005915 OwningExprResult InputInit
5916 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005917 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005918 SourceLocation(),
5919 move(input));
5920 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005921 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005922
Douglas Gregore6600372009-12-23 17:40:29 +00005923 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005924 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005925 }
5926
5927 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005928 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005929
Douglas Gregor084d8552009-03-13 23:49:33 +00005930 // Build the actual expression node.
5931 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5932 SourceLocation());
5933 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005934
Douglas Gregor084d8552009-03-13 23:49:33 +00005935 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005936 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005937 ExprOwningPtr<CallExpr> TheCall(this,
5938 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005939 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005940
5941 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5942 FnDecl))
5943 return ExprError();
5944
5945 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005946 } else {
5947 // We matched a built-in operator. Convert the arguments, then
5948 // break out so that we will build the appropriate built-in
5949 // operator node.
5950 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005951 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005952 return ExprError();
5953
5954 break;
5955 }
5956 }
5957
5958 case OR_No_Viable_Function:
5959 // No viable function; fall through to handling this as a
5960 // built-in operator, which will produce an error message for us.
5961 break;
5962
5963 case OR_Ambiguous:
5964 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5965 << UnaryOperator::getOpcodeStr(Opc)
5966 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005967 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005968 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005969 return ExprError();
5970
5971 case OR_Deleted:
5972 Diag(OpLoc, diag::err_ovl_deleted_oper)
5973 << Best->Function->isDeleted()
5974 << UnaryOperator::getOpcodeStr(Opc)
5975 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005976 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005977 return ExprError();
5978 }
5979
5980 // Either we found no viable overloaded operator or we matched a
5981 // built-in operator. In either case, fall through to trying to
5982 // build a built-in operation.
5983 input.release();
5984 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5985}
5986
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005987/// \brief Create a binary operation that may resolve to an overloaded
5988/// operator.
5989///
5990/// \param OpLoc The location of the operator itself (e.g., '+').
5991///
5992/// \param OpcIn The BinaryOperator::Opcode that describes this
5993/// operator.
5994///
5995/// \param Functions The set of non-member functions that will be
5996/// considered by overload resolution. The caller needs to build this
5997/// set based on the context using, e.g.,
5998/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5999/// set should not contain any member functions; those will be added
6000/// by CreateOverloadedBinOp().
6001///
6002/// \param LHS Left-hand argument.
6003/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006004Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006005Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006006 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006007 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006008 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006009 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006010 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006011
6012 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6013 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6014 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6015
6016 // If either side is type-dependent, create an appropriate dependent
6017 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006018 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006019 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006020 // If there are no functions to store, just build a dependent
6021 // BinaryOperator or CompoundAssignment.
6022 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6023 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6024 Context.DependentTy, OpLoc));
6025
6026 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6027 Context.DependentTy,
6028 Context.DependentTy,
6029 Context.DependentTy,
6030 OpLoc));
6031 }
John McCall4c4c1df2010-01-26 03:27:55 +00006032
6033 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006034 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006035 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006036 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006037 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006038 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006039
John McCall4c4c1df2010-01-26 03:27:55 +00006040 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006041 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006042 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006043 Context.DependentTy,
6044 OpLoc));
6045 }
6046
6047 // If this is the .* operator, which is not overloadable, just
6048 // create a built-in binary operator.
6049 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006050 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006051
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006052 // If this is the assignment operator, we only perform overload resolution
6053 // if the left-hand side is a class or enumeration type. This is actually
6054 // a hack. The standard requires that we do overload resolution between the
6055 // various built-in candidates, but as DR507 points out, this can lead to
6056 // problems. So we do it this way, which pretty much follows what GCC does.
6057 // Note that we go the traditional code path for compound assignment forms.
6058 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006059 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006060
Douglas Gregor084d8552009-03-13 23:49:33 +00006061 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006062 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006063
6064 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006065 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006066
6067 // Add operator candidates that are member functions.
6068 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6069
John McCall4c4c1df2010-01-26 03:27:55 +00006070 // Add candidates from ADL.
6071 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6072 Args, 2,
6073 /*ExplicitTemplateArgs*/ 0,
6074 CandidateSet);
6075
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006076 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006077 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006078
6079 // Perform overload resolution.
6080 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006081 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006082 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006083 // We found a built-in operator or an overloaded operator.
6084 FunctionDecl *FnDecl = Best->Function;
6085
6086 if (FnDecl) {
6087 // We matched an overloaded operator. Build a call to that
6088 // operator.
6089
6090 // Convert the arguments.
6091 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006092 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006093 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006094
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006095 OwningExprResult Arg1
6096 = PerformCopyInitialization(
6097 InitializedEntity::InitializeParameter(
6098 FnDecl->getParamDecl(0)),
6099 SourceLocation(),
6100 Owned(Args[1]));
6101 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006102 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006103
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006104 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006105 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006106 return ExprError();
6107
6108 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006109 } else {
6110 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006111 OwningExprResult Arg0
6112 = PerformCopyInitialization(
6113 InitializedEntity::InitializeParameter(
6114 FnDecl->getParamDecl(0)),
6115 SourceLocation(),
6116 Owned(Args[0]));
6117 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006118 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006119
6120 OwningExprResult Arg1
6121 = PerformCopyInitialization(
6122 InitializedEntity::InitializeParameter(
6123 FnDecl->getParamDecl(1)),
6124 SourceLocation(),
6125 Owned(Args[1]));
6126 if (Arg1.isInvalid())
6127 return ExprError();
6128 Args[0] = LHS = Arg0.takeAs<Expr>();
6129 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006130 }
6131
6132 // Determine the result type
6133 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006134 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006135 ResultTy = ResultTy.getNonReferenceType();
6136
6137 // Build the actual expression node.
6138 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006139 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006140 UsualUnaryConversions(FnExpr);
6141
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006142 ExprOwningPtr<CXXOperatorCallExpr>
6143 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6144 Args, 2, ResultTy,
6145 OpLoc));
6146
6147 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6148 FnDecl))
6149 return ExprError();
6150
6151 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006152 } else {
6153 // We matched a built-in operator. Convert the arguments, then
6154 // break out so that we will build the appropriate built-in
6155 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006156 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006157 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006158 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006159 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006160 return ExprError();
6161
6162 break;
6163 }
6164 }
6165
Douglas Gregor66950a32009-09-30 21:46:01 +00006166 case OR_No_Viable_Function: {
6167 // C++ [over.match.oper]p9:
6168 // If the operator is the operator , [...] and there are no
6169 // viable functions, then the operator is assumed to be the
6170 // built-in operator and interpreted according to clause 5.
6171 if (Opc == BinaryOperator::Comma)
6172 break;
6173
Sebastian Redl027de2a2009-05-21 11:50:50 +00006174 // For class as left operand for assignment or compound assigment operator
6175 // do not fall through to handling in built-in, but report that no overloaded
6176 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006177 OwningExprResult Result = ExprError();
6178 if (Args[0]->getType()->isRecordType() &&
6179 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006180 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6181 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006182 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006183 } else {
6184 // No viable function; try to create a built-in operation, which will
6185 // produce an error. Then, show the non-viable candidates.
6186 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006187 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006188 assert(Result.isInvalid() &&
6189 "C++ binary operator overloading is missing candidates!");
6190 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006191 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006192 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006193 return move(Result);
6194 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006195
6196 case OR_Ambiguous:
6197 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6198 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006199 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006200 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006201 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006202 return ExprError();
6203
6204 case OR_Deleted:
6205 Diag(OpLoc, diag::err_ovl_deleted_oper)
6206 << Best->Function->isDeleted()
6207 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006208 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006209 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006210 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006211 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006212
Douglas Gregor66950a32009-09-30 21:46:01 +00006213 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006214 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006215}
6216
Sebastian Redladba46e2009-10-29 20:17:01 +00006217Action::OwningExprResult
6218Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6219 SourceLocation RLoc,
6220 ExprArg Base, ExprArg Idx) {
6221 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6222 static_cast<Expr*>(Idx.get()) };
6223 DeclarationName OpName =
6224 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6225
6226 // If either side is type-dependent, create an appropriate dependent
6227 // expression.
6228 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6229
John McCall58cc69d2010-01-27 01:50:18 +00006230 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006231 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006232 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006233 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006234 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006235 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006236
6237 Base.release();
6238 Idx.release();
6239 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6240 Args, 2,
6241 Context.DependentTy,
6242 RLoc));
6243 }
6244
6245 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006246 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006247
6248 // Subscript can only be overloaded as a member function.
6249
6250 // Add operator candidates that are member functions.
6251 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6252
6253 // Add builtin operator candidates.
6254 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6255
6256 // Perform overload resolution.
6257 OverloadCandidateSet::iterator Best;
6258 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6259 case OR_Success: {
6260 // We found a built-in operator or an overloaded operator.
6261 FunctionDecl *FnDecl = Best->Function;
6262
6263 if (FnDecl) {
6264 // We matched an overloaded operator. Build a call to that
6265 // operator.
6266
John McCalla0296f72010-03-19 07:35:19 +00006267 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +00006268
Sebastian Redladba46e2009-10-29 20:17:01 +00006269 // Convert the arguments.
6270 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006271 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006272 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006273 return ExprError();
6274
Anders Carlssona68e51e2010-01-29 18:37:50 +00006275 // Convert the arguments.
6276 OwningExprResult InputInit
6277 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6278 FnDecl->getParamDecl(0)),
6279 SourceLocation(),
6280 Owned(Args[1]));
6281 if (InputInit.isInvalid())
6282 return ExprError();
6283
6284 Args[1] = InputInit.takeAs<Expr>();
6285
Sebastian Redladba46e2009-10-29 20:17:01 +00006286 // Determine the result type
6287 QualType ResultTy
6288 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6289 ResultTy = ResultTy.getNonReferenceType();
6290
6291 // Build the actual expression node.
6292 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6293 LLoc);
6294 UsualUnaryConversions(FnExpr);
6295
6296 Base.release();
6297 Idx.release();
6298 ExprOwningPtr<CXXOperatorCallExpr>
6299 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6300 FnExpr, Args, 2,
6301 ResultTy, RLoc));
6302
6303 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6304 FnDecl))
6305 return ExprError();
6306
6307 return MaybeBindToTemporary(TheCall.release());
6308 } else {
6309 // We matched a built-in operator. Convert the arguments, then
6310 // break out so that we will build the appropriate built-in
6311 // operator node.
6312 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006313 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006314 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006315 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006316 return ExprError();
6317
6318 break;
6319 }
6320 }
6321
6322 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006323 if (CandidateSet.empty())
6324 Diag(LLoc, diag::err_ovl_no_oper)
6325 << Args[0]->getType() << /*subscript*/ 0
6326 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6327 else
6328 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6329 << Args[0]->getType()
6330 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006331 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006332 "[]", LLoc);
6333 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006334 }
6335
6336 case OR_Ambiguous:
6337 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6338 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006339 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006340 "[]", LLoc);
6341 return ExprError();
6342
6343 case OR_Deleted:
6344 Diag(LLoc, diag::err_ovl_deleted_oper)
6345 << Best->Function->isDeleted() << "[]"
6346 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006347 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006348 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006349 return ExprError();
6350 }
6351
6352 // We matched a built-in operator; build it.
6353 Base.release();
6354 Idx.release();
6355 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6356 Owned(Args[1]), RLoc);
6357}
6358
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006359/// BuildCallToMemberFunction - Build a call to a member
6360/// function. MemExpr is the expression that refers to the member
6361/// function (and includes the object parameter), Args/NumArgs are the
6362/// arguments to the function call (not including the object
6363/// parameter). The caller needs to validate that the member
6364/// expression refers to a member function or an overloaded member
6365/// function.
John McCall2d74de92009-12-01 22:10:20 +00006366Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006367Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6368 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006369 unsigned NumArgs, SourceLocation *CommaLocs,
6370 SourceLocation RParenLoc) {
6371 // Dig out the member expression. This holds both the object
6372 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006373 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6374
John McCall10eae182009-11-30 22:42:35 +00006375 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006376 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006377 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006378 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006379 if (isa<MemberExpr>(NakedMemExpr)) {
6380 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006381 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006382 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006383 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006384 } else {
6385 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006386 Qualifier = UnresExpr->getQualifier();
6387
John McCall6e9f8f62009-12-03 04:06:58 +00006388 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006389
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006390 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006391 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006392
John McCall2d74de92009-12-01 22:10:20 +00006393 // FIXME: avoid copy.
6394 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6395 if (UnresExpr->hasExplicitTemplateArgs()) {
6396 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6397 TemplateArgs = &TemplateArgsBuffer;
6398 }
6399
John McCall10eae182009-11-30 22:42:35 +00006400 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6401 E = UnresExpr->decls_end(); I != E; ++I) {
6402
John McCall6e9f8f62009-12-03 04:06:58 +00006403 NamedDecl *Func = *I;
6404 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6405 if (isa<UsingShadowDecl>(Func))
6406 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6407
John McCall10eae182009-11-30 22:42:35 +00006408 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006409 // If explicit template arguments were provided, we can't call a
6410 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006411 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006412 continue;
6413
John McCalla0296f72010-03-19 07:35:19 +00006414 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006415 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006416 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006417 } else {
John McCall10eae182009-11-30 22:42:35 +00006418 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006419 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006420 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006421 CandidateSet,
6422 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006423 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006424 }
Mike Stump11289f42009-09-09 15:08:12 +00006425
John McCall10eae182009-11-30 22:42:35 +00006426 DeclarationName DeclName = UnresExpr->getMemberName();
6427
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006428 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006429 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006430 case OR_Success:
6431 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006432 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006433 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006434 break;
6435
6436 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006437 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006438 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006439 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006440 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006441 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006442 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006443
6444 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006445 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006446 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006447 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006448 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006449 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006450
6451 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006452 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006453 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006454 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006455 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006456 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006457 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006458 }
6459
John McCall16df1e52010-03-30 21:47:33 +00006460 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006461
John McCall2d74de92009-12-01 22:10:20 +00006462 // If overload resolution picked a static member, build a
6463 // non-member call based on that function.
6464 if (Method->isStatic()) {
6465 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6466 Args, NumArgs, RParenLoc);
6467 }
6468
John McCall10eae182009-11-30 22:42:35 +00006469 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006470 }
6471
6472 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006473 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006474 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006475 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006476 Method->getResultType().getNonReferenceType(),
6477 RParenLoc));
6478
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006479 // Check for a valid return type.
6480 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6481 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006482 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006483
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006484 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006485 // We only need to do this if there was actually an overload; otherwise
6486 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006487 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006488 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006489 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6490 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006491 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006492 MemExpr->setBase(ObjectArg);
6493
6494 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006495 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006496 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006497 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006498 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006499
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006500 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006501 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006502
John McCall2d74de92009-12-01 22:10:20 +00006503 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006504}
6505
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006506/// BuildCallToObjectOfClassType - Build a call to an object of class
6507/// type (C++ [over.call.object]), which can end up invoking an
6508/// overloaded function call operator (@c operator()) or performing a
6509/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006510Sema::ExprResult
6511Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006512 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006513 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006514 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006515 SourceLocation RParenLoc) {
6516 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006517 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006518
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006519 // C++ [over.call.object]p1:
6520 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006521 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006522 // candidate functions includes at least the function call
6523 // operators of T. The function call operators of T are obtained by
6524 // ordinary lookup of the name operator() in the context of
6525 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006526 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006527 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006528
6529 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006530 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006531 << Object->getSourceRange()))
6532 return true;
6533
John McCall27b18f82009-11-17 02:14:36 +00006534 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6535 LookupQualifiedName(R, Record->getDecl());
6536 R.suppressDiagnostics();
6537
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006538 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006539 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006540 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006541 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006542 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006543 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006544
Douglas Gregorab7897a2008-11-19 22:57:39 +00006545 // C++ [over.call.object]p2:
6546 // In addition, for each conversion function declared in T of the
6547 // form
6548 //
6549 // operator conversion-type-id () cv-qualifier;
6550 //
6551 // where cv-qualifier is the same cv-qualification as, or a
6552 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006553 // denotes the type "pointer to function of (P1,...,Pn) returning
6554 // R", or the type "reference to pointer to function of
6555 // (P1,...,Pn) returning R", or the type "reference to function
6556 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006557 // is also considered as a candidate function. Similarly,
6558 // surrogate call functions are added to the set of candidate
6559 // functions for each conversion function declared in an
6560 // accessible base class provided the function is not hidden
6561 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006562 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006563 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006564 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006565 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006566 NamedDecl *D = *I;
6567 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6568 if (isa<UsingShadowDecl>(D))
6569 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6570
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006571 // Skip over templated conversion functions; they aren't
6572 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006573 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006574 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006575
John McCall6e9f8f62009-12-03 04:06:58 +00006576 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006577
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006578 // Strip the reference type (if any) and then the pointer type (if
6579 // any) to get down to what might be a function type.
6580 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6581 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6582 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006583
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006584 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006585 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006586 Object->getType(), Args, NumArgs,
6587 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006588 }
Mike Stump11289f42009-09-09 15:08:12 +00006589
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006590 // Perform overload resolution.
6591 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006592 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006593 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006594 // Overload resolution succeeded; we'll build the appropriate call
6595 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006596 break;
6597
6598 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006599 if (CandidateSet.empty())
6600 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6601 << Object->getType() << /*call*/ 1
6602 << Object->getSourceRange();
6603 else
6604 Diag(Object->getSourceRange().getBegin(),
6605 diag::err_ovl_no_viable_object_call)
6606 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006607 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006608 break;
6609
6610 case OR_Ambiguous:
6611 Diag(Object->getSourceRange().getBegin(),
6612 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006613 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006614 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006615 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006616
6617 case OR_Deleted:
6618 Diag(Object->getSourceRange().getBegin(),
6619 diag::err_ovl_deleted_object_call)
6620 << Best->Function->isDeleted()
6621 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006622 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006623 break;
Mike Stump11289f42009-09-09 15:08:12 +00006624 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006625
Douglas Gregorab7897a2008-11-19 22:57:39 +00006626 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006627 // We had an error; delete all of the subexpressions and return
6628 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006629 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006630 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006631 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006632 return true;
6633 }
6634
Douglas Gregorab7897a2008-11-19 22:57:39 +00006635 if (Best->Function == 0) {
6636 // Since there is no function declaration, this is one of the
6637 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006638 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006639 = cast<CXXConversionDecl>(
6640 Best->Conversions[0].UserDefined.ConversionFunction);
6641
John McCalla0296f72010-03-19 07:35:19 +00006642 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006643
Douglas Gregorab7897a2008-11-19 22:57:39 +00006644 // We selected one of the surrogate functions that converts the
6645 // object parameter to a function pointer. Perform the conversion
6646 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006647
6648 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006649 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006650 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6651 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006652
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006653 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006654 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006655 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006656 }
6657
John McCalla0296f72010-03-19 07:35:19 +00006658 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006659
Douglas Gregorab7897a2008-11-19 22:57:39 +00006660 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6661 // that calls this method, using Object for the implicit object
6662 // parameter and passing along the remaining arguments.
6663 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006664 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006665
6666 unsigned NumArgsInProto = Proto->getNumArgs();
6667 unsigned NumArgsToCheck = NumArgs;
6668
6669 // Build the full argument list for the method call (the
6670 // implicit object parameter is placed at the beginning of the
6671 // list).
6672 Expr **MethodArgs;
6673 if (NumArgs < NumArgsInProto) {
6674 NumArgsToCheck = NumArgsInProto;
6675 MethodArgs = new Expr*[NumArgsInProto + 1];
6676 } else {
6677 MethodArgs = new Expr*[NumArgs + 1];
6678 }
6679 MethodArgs[0] = Object;
6680 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6681 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006682
6683 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006684 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006685 UsualUnaryConversions(NewFn);
6686
6687 // Once we've built TheCall, all of the expressions are properly
6688 // owned.
6689 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006690 ExprOwningPtr<CXXOperatorCallExpr>
6691 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006692 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006693 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006694 delete [] MethodArgs;
6695
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006696 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6697 Method))
6698 return true;
6699
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006700 // We may have default arguments. If so, we need to allocate more
6701 // slots in the call for them.
6702 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006703 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006704 else if (NumArgs > NumArgsInProto)
6705 NumArgsToCheck = NumArgsInProto;
6706
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006707 bool IsError = false;
6708
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006709 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006710 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006711 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006712 TheCall->setArg(0, Object);
6713
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006714
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006715 // Check the argument types.
6716 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006717 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006718 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006719 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006720
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006721 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006722
6723 OwningExprResult InputInit
6724 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6725 Method->getParamDecl(i)),
6726 SourceLocation(), Owned(Arg));
6727
6728 IsError |= InputInit.isInvalid();
6729 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006730 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006731 OwningExprResult DefArg
6732 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6733 if (DefArg.isInvalid()) {
6734 IsError = true;
6735 break;
6736 }
6737
6738 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006739 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006740
6741 TheCall->setArg(i + 1, Arg);
6742 }
6743
6744 // If this is a variadic call, handle args passed through "...".
6745 if (Proto->isVariadic()) {
6746 // Promote the arguments (C99 6.5.2.2p7).
6747 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6748 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006749 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006750 TheCall->setArg(i + 1, Arg);
6751 }
6752 }
6753
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006754 if (IsError) return true;
6755
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006756 if (CheckFunctionCall(Method, TheCall.get()))
6757 return true;
6758
Douglas Gregore5e775b2010-04-13 15:50:39 +00006759 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006760}
6761
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006762/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006763/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006764/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006765Sema::OwningExprResult
6766Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6767 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006768 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006769
John McCallbc077cf2010-02-08 23:07:23 +00006770 SourceLocation Loc = Base->getExprLoc();
6771
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006772 // C++ [over.ref]p1:
6773 //
6774 // [...] An expression x->m is interpreted as (x.operator->())->m
6775 // for a class object x of type T if T::operator->() exists and if
6776 // the operator is selected as the best match function by the
6777 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006778 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006779 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006780 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006781
John McCallbc077cf2010-02-08 23:07:23 +00006782 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006783 PDiag(diag::err_typecheck_incomplete_tag)
6784 << Base->getSourceRange()))
6785 return ExprError();
6786
John McCall27b18f82009-11-17 02:14:36 +00006787 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6788 LookupQualifiedName(R, BaseRecord->getDecl());
6789 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006790
6791 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006792 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006793 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006794 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006795 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006796
6797 // Perform overload resolution.
6798 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006799 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006800 case OR_Success:
6801 // Overload resolution succeeded; we'll build the call below.
6802 break;
6803
6804 case OR_No_Viable_Function:
6805 if (CandidateSet.empty())
6806 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006807 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006808 else
6809 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006810 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006811 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006812 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006813
6814 case OR_Ambiguous:
6815 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006816 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006817 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006818 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006819
6820 case OR_Deleted:
6821 Diag(OpLoc, diag::err_ovl_deleted_oper)
6822 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006823 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006824 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006825 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006826 }
6827
John McCalla0296f72010-03-19 07:35:19 +00006828 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6829
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006830 // Convert the object parameter.
6831 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006832 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6833 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006834 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006835
6836 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006837 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006838
6839 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006840 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6841 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006842 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006843
6844 QualType ResultTy = Method->getResultType().getNonReferenceType();
6845 ExprOwningPtr<CXXOperatorCallExpr>
6846 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6847 &Base, 1, ResultTy, OpLoc));
6848
6849 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6850 Method))
6851 return ExprError();
6852 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006853}
6854
Douglas Gregorcd695e52008-11-10 20:40:00 +00006855/// FixOverloadedFunctionReference - E is an expression that refers to
6856/// a C++ overloaded function (possibly with some parentheses and
6857/// perhaps a '&' around it). We have resolved the overloaded function
6858/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006859/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00006860Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00006861 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006862 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006863 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6864 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006865 if (SubExpr == PE->getSubExpr())
6866 return PE->Retain();
6867
6868 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6869 }
6870
6871 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006872 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6873 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006874 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006875 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006876 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006877 if (SubExpr == ICE->getSubExpr())
6878 return ICE->Retain();
6879
6880 return new (Context) ImplicitCastExpr(ICE->getType(),
6881 ICE->getCastKind(),
6882 SubExpr,
6883 ICE->isLvalueCast());
6884 }
6885
6886 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006887 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006888 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006889 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6890 if (Method->isStatic()) {
6891 // Do nothing: static member functions aren't any different
6892 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006893 } else {
John McCalle66edc12009-11-24 19:00:30 +00006894 // Fix the sub expression, which really has to be an
6895 // UnresolvedLookupExpr holding an overloaded member function
6896 // or template.
John McCall16df1e52010-03-30 21:47:33 +00006897 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6898 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00006899 if (SubExpr == UnOp->getSubExpr())
6900 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006901
John McCalld14a8642009-11-21 08:51:07 +00006902 assert(isa<DeclRefExpr>(SubExpr)
6903 && "fixed to something other than a decl ref");
6904 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6905 && "fixed to a member ref with no nested name qualifier");
6906
6907 // We have taken the address of a pointer to member
6908 // function. Perform the computation here so that we get the
6909 // appropriate pointer to member type.
6910 QualType ClassType
6911 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6912 QualType MemPtrType
6913 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6914
6915 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6916 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006917 }
6918 }
John McCall16df1e52010-03-30 21:47:33 +00006919 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6920 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006921 if (SubExpr == UnOp->getSubExpr())
6922 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006923
Douglas Gregor51c538b2009-11-20 19:42:02 +00006924 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6925 Context.getPointerType(SubExpr->getType()),
6926 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006927 }
John McCalld14a8642009-11-21 08:51:07 +00006928
6929 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006930 // FIXME: avoid copy.
6931 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006932 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006933 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6934 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006935 }
6936
John McCalld14a8642009-11-21 08:51:07 +00006937 return DeclRefExpr::Create(Context,
6938 ULE->getQualifier(),
6939 ULE->getQualifierRange(),
6940 Fn,
6941 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006942 Fn->getType(),
6943 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006944 }
6945
John McCall10eae182009-11-30 22:42:35 +00006946 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006947 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006948 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6949 if (MemExpr->hasExplicitTemplateArgs()) {
6950 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6951 TemplateArgs = &TemplateArgsBuffer;
6952 }
John McCall6b51f282009-11-23 01:53:49 +00006953
John McCall2d74de92009-12-01 22:10:20 +00006954 Expr *Base;
6955
6956 // If we're filling in
6957 if (MemExpr->isImplicitAccess()) {
6958 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6959 return DeclRefExpr::Create(Context,
6960 MemExpr->getQualifier(),
6961 MemExpr->getQualifierRange(),
6962 Fn,
6963 MemExpr->getMemberLoc(),
6964 Fn->getType(),
6965 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006966 } else {
6967 SourceLocation Loc = MemExpr->getMemberLoc();
6968 if (MemExpr->getQualifier())
6969 Loc = MemExpr->getQualifierRange().getBegin();
6970 Base = new (Context) CXXThisExpr(Loc,
6971 MemExpr->getBaseType(),
6972 /*isImplicit=*/true);
6973 }
John McCall2d74de92009-12-01 22:10:20 +00006974 } else
6975 Base = MemExpr->getBase()->Retain();
6976
6977 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006978 MemExpr->isArrow(),
6979 MemExpr->getQualifier(),
6980 MemExpr->getQualifierRange(),
6981 Fn,
John McCall16df1e52010-03-30 21:47:33 +00006982 Found,
John McCall6b51f282009-11-23 01:53:49 +00006983 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006984 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006985 Fn->getType());
6986 }
6987
Douglas Gregor51c538b2009-11-20 19:42:02 +00006988 assert(false && "Invalid reference to overloaded function");
6989 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006990}
6991
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006992Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00006993 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006994 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00006995 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006996}
6997
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006998} // end namespace clang