blob: b87fa7d51ea189a829fb0c51e48c61bbb77f3845 [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() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000377 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000378 return true;
379
380 // C++ [temp.over.link]p4:
381 // The signature of a function template consists of its function
382 // signature, its return type and its template parameter list. The names
383 // of the template parameters are significant only for establishing the
384 // relationship between the template parameters and the rest of the
385 // signature.
386 //
387 // We check the return type and template parameter lists for function
388 // templates first; the remaining checks follow.
389 if (NewTemplate &&
390 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
391 OldTemplate->getTemplateParameters(),
392 false, TPL_TemplateMatch) ||
393 OldType->getResultType() != NewType->getResultType()))
394 return true;
395
396 // If the function is a class member, its signature includes the
397 // cv-qualifiers (if any) on the function itself.
398 //
399 // As part of this, also check whether one of the member functions
400 // is static, in which case they are not overloads (C++
401 // 13.1p2). While not part of the definition of the signature,
402 // this check is important to determine whether these functions
403 // can be overloaded.
404 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
405 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
406 if (OldMethod && NewMethod &&
407 !OldMethod->isStatic() && !NewMethod->isStatic() &&
408 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
409 return true;
410
411 // The signatures match; this is not an overload.
412 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000413}
414
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000415/// TryImplicitConversion - Attempt to perform an implicit conversion
416/// from the given expression (Expr) to the given type (ToType). This
417/// function returns an implicit conversion sequence that can be used
418/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000419///
420/// void f(float f);
421/// void g(int i) { f(i); }
422///
423/// this routine would produce an implicit conversion sequence to
424/// describe the initialization of f from i, which will be a standard
425/// conversion sequence containing an lvalue-to-rvalue conversion (C++
426/// 4.1) followed by a floating-integral conversion (C++ 4.9).
427//
428/// Note that this routine only determines how the conversion can be
429/// performed; it does not actually perform the conversion. As such,
430/// it will not produce any diagnostics if no conversion is available,
431/// but will instead return an implicit conversion sequence of kind
432/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000433///
434/// If @p SuppressUserConversions, then user-defined conversions are
435/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000436/// If @p AllowExplicit, then explicit user-defined conversions are
437/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000439Sema::TryImplicitConversion(Expr* From, QualType ToType,
440 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000441 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000442 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000443 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000444 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000445 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000446 return ICS;
447 }
448
449 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000450 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000451 return ICS;
452 }
453
Douglas Gregor5ab11652010-04-17 22:01:05 +0000454 if (SuppressUserConversions) {
455 // C++ [over.ics.user]p4:
456 // A conversion of an expression of class type to the same class
457 // type is given Exact Match rank, and a conversion of an
458 // expression of class type to a base class of that type is
459 // given Conversion rank, in spite of the fact that a copy/move
460 // constructor (i.e., a user-defined conversion function) is
461 // called for those cases.
462 QualType FromType = From->getType();
463 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
464 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
465 IsDerivedFrom(FromType, ToType))) {
466 // We're not in the case above, so there is no conversion that
467 // we can perform.
468 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
469 return ICS;
470 }
471
472 ICS.setStandard();
473 ICS.Standard.setAsIdentityConversion();
474 ICS.Standard.setFromType(FromType);
475 ICS.Standard.setAllToTypes(ToType);
476
477 // We don't actually check at this point whether there is a valid
478 // copy/move constructor, since overloading just assumes that it
479 // exists. When we actually perform initialization, we'll find the
480 // appropriate constructor to copy the returned object, if needed.
481 ICS.Standard.CopyConstructor = 0;
482
483 // Determine whether this is considered a derived-to-base conversion.
484 if (!Context.hasSameUnqualifiedType(FromType, ToType))
485 ICS.Standard.Second = ICK_Derived_To_Base;
486
487 return ICS;
488 }
489
490 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000491 OverloadCandidateSet Conversions(From->getExprLoc());
492 OverloadingResult UserDefResult
493 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000494 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000495
496 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000497 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000498 // C++ [over.ics.user]p4:
499 // A conversion of an expression of class type to the same class
500 // type is given Exact Match rank, and a conversion of an
501 // expression of class type to a base class of that type is
502 // given Conversion rank, in spite of the fact that a copy
503 // constructor (i.e., a user-defined conversion function) is
504 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000505 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000506 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000507 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000508 = Context.getCanonicalType(From->getType().getUnqualifiedType());
509 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000510 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000511 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000512 // Turn this into a "standard" conversion sequence, so that it
513 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000514 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000515 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000516 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000517 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000518 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000519 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000520 ICS.Standard.Second = ICK_Derived_To_Base;
521 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000522 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000523
524 // C++ [over.best.ics]p4:
525 // However, when considering the argument of a user-defined
526 // conversion function that is a candidate by 13.3.1.3 when
527 // invoked for the copying of the temporary in the second step
528 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
529 // 13.3.1.6 in all cases, only standard conversion sequences and
530 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000531 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000532 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000533 }
John McCalle8c8cd22010-01-13 22:30:33 +0000534 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000535 ICS.setAmbiguous();
536 ICS.Ambiguous.setFromType(From->getType());
537 ICS.Ambiguous.setToType(ToType);
538 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
539 Cand != Conversions.end(); ++Cand)
540 if (Cand->Viable)
541 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000542 } else {
John McCall65eb8792010-02-25 01:37:24 +0000543 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000544 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000545
546 return ICS;
547}
548
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000549/// PerformImplicitConversion - Perform an implicit conversion of the
550/// expression From to the type ToType. Returns true if there was an
551/// error, false otherwise. The expression From is replaced with the
552/// converted expression. Flavor is the kind of conversion we're
553/// performing, used in the error message. If @p AllowExplicit,
554/// explicit user-defined conversions are permitted.
555bool
556Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
557 AssignmentAction Action, bool AllowExplicit) {
558 ImplicitConversionSequence ICS;
559 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
560}
561
562bool
563Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
564 AssignmentAction Action, bool AllowExplicit,
565 ImplicitConversionSequence& ICS) {
566 ICS = TryImplicitConversion(From, ToType,
567 /*SuppressUserConversions=*/false,
568 AllowExplicit,
569 /*InOverloadResolution=*/false);
570 return PerformImplicitConversion(From, ToType, ICS, Action);
571}
572
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000573/// \brief Determine whether the conversion from FromType to ToType is a valid
574/// conversion that strips "noreturn" off the nested function type.
575static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
576 QualType ToType, QualType &ResultTy) {
577 if (Context.hasSameUnqualifiedType(FromType, ToType))
578 return false;
579
580 // Strip the noreturn off the type we're converting from; noreturn can
581 // safely be removed.
582 FromType = Context.getNoReturnType(FromType, false);
583 if (!Context.hasSameUnqualifiedType(FromType, ToType))
584 return false;
585
586 ResultTy = FromType;
587 return true;
588}
589
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000590/// IsStandardConversion - Determines whether there is a standard
591/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
592/// expression From to the type ToType. Standard conversion sequences
593/// only consider non-class types; for conversions that involve class
594/// types, use TryImplicitConversion. If a conversion exists, SCS will
595/// contain the standard conversion sequence required to perform this
596/// conversion and this routine will return true. Otherwise, this
597/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000598bool
599Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000600 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000601 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602 QualType FromType = From->getType();
603
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000604 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000605 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000606 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000607 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000608 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000609 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000610
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000611 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000612 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000613 if (FromType->isRecordType() || ToType->isRecordType()) {
614 if (getLangOptions().CPlusPlus)
615 return false;
616
Mike Stump11289f42009-09-09 15:08:12 +0000617 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000618 }
619
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000620 // The first conversion can be an lvalue-to-rvalue conversion,
621 // array-to-pointer conversion, or function-to-pointer conversion
622 // (C++ 4p1).
623
Douglas Gregor980fb162010-04-29 18:24:40 +0000624 if (FromType == Context.OverloadTy) {
625 DeclAccessPair AccessPair;
626 if (FunctionDecl *Fn
627 = ResolveAddressOfOverloadedFunction(From, ToType, false,
628 AccessPair)) {
629 // We were able to resolve the address of the overloaded function,
630 // so we can convert to the type of that function.
631 FromType = Fn->getType();
632 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
633 if (!Method->isStatic()) {
634 Type *ClassType
635 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
636 FromType = Context.getMemberPointerType(FromType, ClassType);
637 }
638 }
639
640 // If the "from" expression takes the address of the overloaded
641 // function, update the type of the resulting expression accordingly.
642 if (FromType->getAs<FunctionType>())
643 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
644 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
645 FromType = Context.getPointerType(FromType);
646
647 // Check that we've computed the proper type after overload resolution.
648 assert(Context.hasSameType(FromType,
649 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
650 } else {
651 return false;
652 }
653 }
Mike Stump11289f42009-09-09 15:08:12 +0000654 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000655 // An lvalue (3.10) of a non-function, non-array type T can be
656 // converted to an rvalue.
657 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000658 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000659 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000660 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000662
663 // If T is a non-class type, the type of the rvalue is the
664 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000665 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
666 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000667 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000668 } else if (FromType->isArrayType()) {
669 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000670 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671
672 // An lvalue or rvalue of type "array of N T" or "array of unknown
673 // bound of T" can be converted to an rvalue of type "pointer to
674 // T" (C++ 4.2p1).
675 FromType = Context.getArrayDecayedType(FromType);
676
677 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
678 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000679 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000680
681 // For the purpose of ranking in overload resolution
682 // (13.3.3.1.1), this conversion is considered an
683 // array-to-pointer conversion followed by a qualification
684 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000685 SCS.Second = ICK_Identity;
686 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000687 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000688 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000689 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000690 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
691 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000692 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000693
694 // An lvalue of function type T can be converted to an rvalue of
695 // type "pointer to T." The result is a pointer to the
696 // function. (C++ 4.3p1).
697 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000698 } else {
699 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000700 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000701 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000702 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000703
704 // The second conversion can be an integral promotion, floating
705 // point promotion, integral conversion, floating point conversion,
706 // floating-integral conversion, pointer conversion,
707 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000708 // For overloading in C, this can also be a "compatible-type"
709 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000710 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000711 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000712 // The unqualified versions of the types are the same: there's no
713 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000714 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000715 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000716 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000717 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000718 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000719 } else if (IsFloatingPointPromotion(FromType, ToType)) {
720 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000721 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000723 } else if (IsComplexPromotion(FromType, ToType)) {
724 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000725 SCS.Second = ICK_Complex_Promotion;
726 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000727 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000728 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000729 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000730 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000731 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000732 } else if (FromType->isComplexType() && ToType->isComplexType()) {
733 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000734 SCS.Second = ICK_Complex_Conversion;
735 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000736 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
737 (ToType->isComplexType() && FromType->isArithmeticType())) {
738 // Complex-real conversions (C99 6.3.1.7)
739 SCS.Second = ICK_Complex_Real;
740 FromType = ToType.getUnqualifiedType();
741 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
742 // Floating point conversions (C++ 4.8).
743 SCS.Second = ICK_Floating_Conversion;
744 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000745 } else if ((FromType->isFloatingType() &&
746 ToType->isIntegralType() && (!ToType->isBooleanType() &&
747 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000748 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000749 ToType->isFloatingType())) {
750 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000751 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000753 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
754 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000755 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000756 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000757 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000758 } else if (IsMemberPointerConversion(From, FromType, ToType,
759 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000760 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000761 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000762 } else if (ToType->isBooleanType() &&
763 (FromType->isArithmeticType() ||
764 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000765 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000766 FromType->isBlockPointerType() ||
767 FromType->isMemberPointerType() ||
768 FromType->isNullPtrType())) {
769 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000770 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000771 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000772 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000773 Context.typesAreCompatible(ToType, FromType)) {
774 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000775 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000776 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
777 // Treat a conversion that strips "noreturn" as an identity conversion.
778 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000779 } else {
780 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000781 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000782 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000783 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000785 QualType CanonFrom;
786 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000788 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000789 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000790 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000791 CanonFrom = Context.getCanonicalType(FromType);
792 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000793 } else {
794 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000795 SCS.Third = ICK_Identity;
796
Mike Stump11289f42009-09-09 15:08:12 +0000797 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000798 // [...] Any difference in top-level cv-qualification is
799 // subsumed by the initialization itself and does not constitute
800 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000801 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000802 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000803 if (CanonFrom.getLocalUnqualifiedType()
804 == CanonTo.getLocalUnqualifiedType() &&
805 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000806 FromType = ToType;
807 CanonFrom = CanonTo;
808 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000809 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000810 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000811
812 // If we have not converted the argument type to the parameter type,
813 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000814 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000815 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000817 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000818}
819
820/// IsIntegralPromotion - Determines whether the conversion from the
821/// expression From (whose potentially-adjusted type is FromType) to
822/// ToType is an integral promotion (C++ 4.5). If so, returns true and
823/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000824bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000825 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000826 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000827 if (!To) {
828 return false;
829 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830
831 // An rvalue of type char, signed char, unsigned char, short int, or
832 // unsigned short int can be converted to an rvalue of type int if
833 // int can represent all the values of the source type; otherwise,
834 // the source rvalue can be converted to an rvalue of type unsigned
835 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000836 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
837 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000838 if (// We can promote any signed, promotable integer type to an int
839 (FromType->isSignedIntegerType() ||
840 // We can promote any unsigned integer type whose size is
841 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000842 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000843 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000844 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000845 }
846
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847 return To->getKind() == BuiltinType::UInt;
848 }
849
850 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
851 // can be converted to an rvalue of the first of the following types
852 // that can represent all the values of its underlying type: int,
853 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000854
855 // We pre-calculate the promotion type for enum types.
856 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
857 if (ToType->isIntegerType())
858 return Context.hasSameUnqualifiedType(ToType,
859 FromEnumType->getDecl()->getPromotionType());
860
861 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000862 // Determine whether the type we're converting from is signed or
863 // unsigned.
864 bool FromIsSigned;
865 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000866
867 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
868 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869
870 // The types we'll try to promote to, in the appropriate
871 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000872 QualType PromoteTypes[6] = {
873 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000874 Context.LongTy, Context.UnsignedLongTy ,
875 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000876 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000877 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000878 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
879 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000880 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000881 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
882 // We found the type that we can promote to. If this is the
883 // type we wanted, we have a promotion. Otherwise, no
884 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000885 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886 }
887 }
888 }
889
890 // An rvalue for an integral bit-field (9.6) can be converted to an
891 // rvalue of type int if int can represent all the values of the
892 // bit-field; otherwise, it can be converted to unsigned int if
893 // unsigned int can represent all the values of the bit-field. If
894 // the bit-field is larger yet, no integral promotion applies to
895 // it. If the bit-field has an enumerated type, it is treated as any
896 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000897 // FIXME: We should delay checking of bit-fields until we actually perform the
898 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000899 using llvm::APSInt;
900 if (From)
901 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000902 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000903 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
904 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
905 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
906 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000908 // Are we promoting to an int from a bitfield that fits in an int?
909 if (BitWidth < ToSize ||
910 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
911 return To->getKind() == BuiltinType::Int;
912 }
Mike Stump11289f42009-09-09 15:08:12 +0000913
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000914 // Are we promoting to an unsigned int from an unsigned bitfield
915 // that fits into an unsigned int?
916 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
917 return To->getKind() == BuiltinType::UInt;
918 }
Mike Stump11289f42009-09-09 15:08:12 +0000919
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000920 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000921 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000922 }
Mike Stump11289f42009-09-09 15:08:12 +0000923
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000924 // An rvalue of type bool can be converted to an rvalue of type int,
925 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000926 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000927 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000928 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000929
930 return false;
931}
932
933/// IsFloatingPointPromotion - Determines whether the conversion from
934/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
935/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000936bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000937 /// An rvalue of type float can be converted to an rvalue of type
938 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000939 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
940 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000941 if (FromBuiltin->getKind() == BuiltinType::Float &&
942 ToBuiltin->getKind() == BuiltinType::Double)
943 return true;
944
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000945 // C99 6.3.1.5p1:
946 // When a float is promoted to double or long double, or a
947 // double is promoted to long double [...].
948 if (!getLangOptions().CPlusPlus &&
949 (FromBuiltin->getKind() == BuiltinType::Float ||
950 FromBuiltin->getKind() == BuiltinType::Double) &&
951 (ToBuiltin->getKind() == BuiltinType::LongDouble))
952 return true;
953 }
954
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000955 return false;
956}
957
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000958/// \brief Determine if a conversion is a complex promotion.
959///
960/// A complex promotion is defined as a complex -> complex conversion
961/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000962/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000963bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000964 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000965 if (!FromComplex)
966 return false;
967
John McCall9dd450b2009-09-21 23:43:11 +0000968 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000969 if (!ToComplex)
970 return false;
971
972 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000973 ToComplex->getElementType()) ||
974 IsIntegralPromotion(0, FromComplex->getElementType(),
975 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000976}
977
Douglas Gregor237f96c2008-11-26 23:31:11 +0000978/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
979/// the pointer type FromPtr to a pointer to type ToPointee, with the
980/// same type qualifiers as FromPtr has on its pointee type. ToType,
981/// if non-empty, will be a pointer to ToType that may or may not have
982/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000983static QualType
984BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000985 QualType ToPointee, QualType ToType,
986 ASTContext &Context) {
987 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
988 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000989 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000990
991 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000992 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000993 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000994 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000995 return ToType;
996
997 // Build a pointer to ToPointee. It has the right qualifiers
998 // already.
999 return Context.getPointerType(ToPointee);
1000 }
1001
1002 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001003 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001004 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1005 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001006}
1007
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001008/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1009/// the FromType, which is an objective-c pointer, to ToType, which may or may
1010/// not have the right set of qualifiers.
1011static QualType
1012BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1013 QualType ToType,
1014 ASTContext &Context) {
1015 QualType CanonFromType = Context.getCanonicalType(FromType);
1016 QualType CanonToType = Context.getCanonicalType(ToType);
1017 Qualifiers Quals = CanonFromType.getQualifiers();
1018
1019 // Exact qualifier match -> return the pointer type we're converting to.
1020 if (CanonToType.getLocalQualifiers() == Quals)
1021 return ToType;
1022
1023 // Just build a canonical type that has the right qualifiers.
1024 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1025}
1026
Mike Stump11289f42009-09-09 15:08:12 +00001027static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001028 bool InOverloadResolution,
1029 ASTContext &Context) {
1030 // Handle value-dependent integral null pointer constants correctly.
1031 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1032 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1033 Expr->getType()->isIntegralType())
1034 return !InOverloadResolution;
1035
Douglas Gregor56751b52009-09-25 04:25:58 +00001036 return Expr->isNullPointerConstant(Context,
1037 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1038 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001039}
Mike Stump11289f42009-09-09 15:08:12 +00001040
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001041/// IsPointerConversion - Determines whether the conversion of the
1042/// expression From, which has the (possibly adjusted) type FromType,
1043/// can be converted to the type ToType via a pointer conversion (C++
1044/// 4.10). If so, returns true and places the converted type (that
1045/// might differ from ToType in its cv-qualifiers at some level) into
1046/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001047///
Douglas Gregora29dc052008-11-27 01:19:21 +00001048/// This routine also supports conversions to and from block pointers
1049/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1050/// pointers to interfaces. FIXME: Once we've determined the
1051/// appropriate overloading rules for Objective-C, we may want to
1052/// split the Objective-C checks into a different routine; however,
1053/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001054/// conversions, so for now they live here. IncompatibleObjC will be
1055/// set if the conversion is an allowed Objective-C conversion that
1056/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001057bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001058 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001059 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001060 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001061 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001062 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1063 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001064
Mike Stump11289f42009-09-09 15:08:12 +00001065 // Conversion from a null pointer constant to any Objective-C pointer type.
1066 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001067 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001068 ConvertedType = ToType;
1069 return true;
1070 }
1071
Douglas Gregor231d1c62008-11-27 00:15:41 +00001072 // Blocks: Block pointers can be converted to void*.
1073 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001074 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001075 ConvertedType = ToType;
1076 return true;
1077 }
1078 // Blocks: A null pointer constant can be converted to a block
1079 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001080 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001081 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001082 ConvertedType = ToType;
1083 return true;
1084 }
1085
Sebastian Redl576fd422009-05-10 18:38:11 +00001086 // If the left-hand-side is nullptr_t, the right side can be a null
1087 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001088 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001089 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001090 ConvertedType = ToType;
1091 return true;
1092 }
1093
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001094 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001095 if (!ToTypePtr)
1096 return false;
1097
1098 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001099 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100 ConvertedType = ToType;
1101 return true;
1102 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001103
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001104 // Beyond this point, both types need to be pointers
1105 // , including objective-c pointers.
1106 QualType ToPointeeType = ToTypePtr->getPointeeType();
1107 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1108 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1109 ToType, Context);
1110 return true;
1111
1112 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001113 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001114 if (!FromTypePtr)
1115 return false;
1116
1117 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001118
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119 // An rvalue of type "pointer to cv T," where T is an object type,
1120 // can be converted to an rvalue of type "pointer to cv void" (C++
1121 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001122 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001124 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001125 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126 return true;
1127 }
1128
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001129 // When we're overloading in C, we allow a special kind of pointer
1130 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001131 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001132 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001133 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001134 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001135 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001136 return true;
1137 }
1138
Douglas Gregor5c407d92008-10-23 00:40:37 +00001139 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001140 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001141 // An rvalue of type "pointer to cv D," where D is a class type,
1142 // can be converted to an rvalue of type "pointer to cv B," where
1143 // B is a base class (clause 10) of D. If B is an inaccessible
1144 // (clause 11) or ambiguous (10.2) base class of D, a program that
1145 // necessitates this conversion is ill-formed. The result of the
1146 // conversion is a pointer to the base class sub-object of the
1147 // derived class object. The null pointer value is converted to
1148 // the null pointer value of the destination type.
1149 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001150 // Note that we do not check for ambiguity or inaccessibility
1151 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001152 if (getLangOptions().CPlusPlus &&
1153 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001154 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001155 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001156 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001157 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001158 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001159 ToType, Context);
1160 return true;
1161 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001162
Douglas Gregora119f102008-12-19 19:13:09 +00001163 return false;
1164}
1165
1166/// isObjCPointerConversion - Determines whether this is an
1167/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1168/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001169bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001170 QualType& ConvertedType,
1171 bool &IncompatibleObjC) {
1172 if (!getLangOptions().ObjC1)
1173 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001174
Steve Naroff7cae42b2009-07-10 23:34:53 +00001175 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001176 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001177 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001178 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001179
Steve Naroff7cae42b2009-07-10 23:34:53 +00001180 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001181 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001182 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001183 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001184 ConvertedType = ToType;
1185 return true;
1186 }
1187 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001188 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001189 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001190 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001191 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001192 ConvertedType = ToType;
1193 return true;
1194 }
1195 // Objective C++: We're able to convert from a pointer to an
1196 // interface to a pointer to a different interface.
1197 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001198 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1199 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1200 if (getLangOptions().CPlusPlus && LHS && RHS &&
1201 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1202 FromObjCPtr->getPointeeType()))
1203 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001204 ConvertedType = ToType;
1205 return true;
1206 }
1207
1208 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1209 // Okay: this is some kind of implicit downcast of Objective-C
1210 // interfaces, which is permitted. However, we're going to
1211 // complain about it.
1212 IncompatibleObjC = true;
1213 ConvertedType = FromType;
1214 return true;
1215 }
Mike Stump11289f42009-09-09 15:08:12 +00001216 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001217 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001218 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001219 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001220 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001221 else if (const BlockPointerType *ToBlockPtr =
1222 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001223 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001224 // to a block pointer type.
1225 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1226 ConvertedType = ToType;
1227 return true;
1228 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001229 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001230 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001231 else if (FromType->getAs<BlockPointerType>() &&
1232 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1233 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001234 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001235 ConvertedType = ToType;
1236 return true;
1237 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001238 else
Douglas Gregora119f102008-12-19 19:13:09 +00001239 return false;
1240
Douglas Gregor033f56d2008-12-23 00:53:59 +00001241 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001242 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001243 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001244 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001245 FromPointeeType = FromBlockPtr->getPointeeType();
1246 else
Douglas Gregora119f102008-12-19 19:13:09 +00001247 return false;
1248
Douglas Gregora119f102008-12-19 19:13:09 +00001249 // If we have pointers to pointers, recursively check whether this
1250 // is an Objective-C conversion.
1251 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1252 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1253 IncompatibleObjC)) {
1254 // We always complain about this conversion.
1255 IncompatibleObjC = true;
1256 ConvertedType = ToType;
1257 return true;
1258 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001259 // Allow conversion of pointee being objective-c pointer to another one;
1260 // as in I* to id.
1261 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1262 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1263 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1264 IncompatibleObjC)) {
1265 ConvertedType = ToType;
1266 return true;
1267 }
1268
Douglas Gregor033f56d2008-12-23 00:53:59 +00001269 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001270 // differences in the argument and result types are in Objective-C
1271 // pointer conversions. If so, we permit the conversion (but
1272 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001273 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001274 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001275 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001276 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001277 if (FromFunctionType && ToFunctionType) {
1278 // If the function types are exactly the same, this isn't an
1279 // Objective-C pointer conversion.
1280 if (Context.getCanonicalType(FromPointeeType)
1281 == Context.getCanonicalType(ToPointeeType))
1282 return false;
1283
1284 // Perform the quick checks that will tell us whether these
1285 // function types are obviously different.
1286 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1287 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1288 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1289 return false;
1290
1291 bool HasObjCConversion = false;
1292 if (Context.getCanonicalType(FromFunctionType->getResultType())
1293 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1294 // Okay, the types match exactly. Nothing to do.
1295 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1296 ToFunctionType->getResultType(),
1297 ConvertedType, IncompatibleObjC)) {
1298 // Okay, we have an Objective-C pointer conversion.
1299 HasObjCConversion = true;
1300 } else {
1301 // Function types are too different. Abort.
1302 return false;
1303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
Douglas Gregora119f102008-12-19 19:13:09 +00001305 // Check argument types.
1306 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1307 ArgIdx != NumArgs; ++ArgIdx) {
1308 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1309 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1310 if (Context.getCanonicalType(FromArgType)
1311 == Context.getCanonicalType(ToArgType)) {
1312 // Okay, the types match exactly. Nothing to do.
1313 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1314 ConvertedType, IncompatibleObjC)) {
1315 // Okay, we have an Objective-C pointer conversion.
1316 HasObjCConversion = true;
1317 } else {
1318 // Argument types are too different. Abort.
1319 return false;
1320 }
1321 }
1322
1323 if (HasObjCConversion) {
1324 // We had an Objective-C conversion. Allow this pointer
1325 // conversion, but complain about it.
1326 ConvertedType = ToType;
1327 IncompatibleObjC = true;
1328 return true;
1329 }
1330 }
1331
Sebastian Redl72b597d2009-01-25 19:43:20 +00001332 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001333}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001334
1335/// FunctionArgTypesAreEqual - This routine checks two function proto types
1336/// for equlity of their argument types. Caller has already checked that
1337/// they have same number of arguments. This routine assumes that Objective-C
1338/// pointer types which only differ in their protocol qualifiers are equal.
1339bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1340 FunctionProtoType* NewType){
1341 if (!getLangOptions().ObjC1)
1342 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1343 NewType->arg_type_begin());
1344
1345 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1346 N = NewType->arg_type_begin(),
1347 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1348 QualType ToType = (*O);
1349 QualType FromType = (*N);
1350 if (ToType != FromType) {
1351 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1352 if (const PointerType *PTFr = FromType->getAs<PointerType>())
1353 if (PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1354 PTFr->getPointeeType()->isObjCQualifiedIdType() ||
1355 PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1356 PTFr->getPointeeType()->isObjCQualifiedClassType())
1357 continue;
1358 }
1359 else if (ToType->isObjCObjectPointerType() &&
1360 FromType->isObjCObjectPointerType()) {
1361 QualType ToInterfaceTy = ToType->getPointeeType();
1362 QualType FromInterfaceTy = FromType->getPointeeType();
1363 if (const ObjCInterfaceType *OITTo =
1364 ToInterfaceTy->getAs<ObjCInterfaceType>())
1365 if (const ObjCInterfaceType *OITFr =
1366 FromInterfaceTy->getAs<ObjCInterfaceType>())
1367 if (OITTo->getDecl() == OITFr->getDecl())
1368 continue;
1369 }
1370 return false;
1371 }
1372 }
1373 return true;
1374}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001375
Douglas Gregor39c16d42008-10-24 04:54:22 +00001376/// CheckPointerConversion - Check the pointer conversion from the
1377/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001378/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001379/// conversions for which IsPointerConversion has already returned
1380/// true. It returns true and produces a diagnostic if there was an
1381/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001382bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001383 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001384 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001385 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001386 QualType FromType = From->getType();
1387
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001388 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1389 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001390 QualType FromPointeeType = FromPtrType->getPointeeType(),
1391 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001392
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001393 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1394 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001395 // We must have a derived-to-base conversion. Check an
1396 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001397 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1398 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001399 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001400 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001401 return true;
1402
1403 // The conversion was successful.
1404 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001405 }
1406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001408 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001409 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001410 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001411 // Objective-C++ conversions are always okay.
1412 // FIXME: We should have a different class of conversions for the
1413 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001414 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001415 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001416
Steve Naroff7cae42b2009-07-10 23:34:53 +00001417 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001418 return false;
1419}
1420
Sebastian Redl72b597d2009-01-25 19:43:20 +00001421/// IsMemberPointerConversion - Determines whether the conversion of the
1422/// expression From, which has the (possibly adjusted) type FromType, can be
1423/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1424/// If so, returns true and places the converted type (that might differ from
1425/// ToType in its cv-qualifiers at some level) into ConvertedType.
1426bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001427 QualType ToType,
1428 bool InOverloadResolution,
1429 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001430 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001431 if (!ToTypePtr)
1432 return false;
1433
1434 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001435 if (From->isNullPointerConstant(Context,
1436 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1437 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001438 ConvertedType = ToType;
1439 return true;
1440 }
1441
1442 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001443 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001444 if (!FromTypePtr)
1445 return false;
1446
1447 // A pointer to member of B can be converted to a pointer to member of D,
1448 // where D is derived from B (C++ 4.11p2).
1449 QualType FromClass(FromTypePtr->getClass(), 0);
1450 QualType ToClass(ToTypePtr->getClass(), 0);
1451 // FIXME: What happens when these are dependent? Is this function even called?
1452
1453 if (IsDerivedFrom(ToClass, FromClass)) {
1454 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1455 ToClass.getTypePtr());
1456 return true;
1457 }
1458
1459 return false;
1460}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001461
Sebastian Redl72b597d2009-01-25 19:43:20 +00001462/// CheckMemberPointerConversion - Check the member pointer conversion from the
1463/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001464/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001465/// for which IsMemberPointerConversion has already returned true. It returns
1466/// true and produces a diagnostic if there was an error, or returns false
1467/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001468bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001469 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001470 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001471 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001472 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001473 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001474 if (!FromPtrType) {
1475 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001476 assert(From->isNullPointerConstant(Context,
1477 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001478 "Expr must be null pointer constant!");
1479 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001480 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001481 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001482
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001483 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001484 assert(ToPtrType && "No member pointer cast has a target type "
1485 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001486
Sebastian Redled8f2002009-01-28 18:33:18 +00001487 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1488 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001489
Sebastian Redled8f2002009-01-28 18:33:18 +00001490 // FIXME: What about dependent types?
1491 assert(FromClass->isRecordType() && "Pointer into non-class.");
1492 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001493
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001494 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001495 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001496 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1497 assert(DerivationOkay &&
1498 "Should not have been called if derivation isn't OK.");
1499 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001500
Sebastian Redled8f2002009-01-28 18:33:18 +00001501 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1502 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001503 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1504 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1505 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1506 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001507 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001508
Douglas Gregor89ee6822009-02-28 01:32:25 +00001509 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001510 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1511 << FromClass << ToClass << QualType(VBase, 0)
1512 << From->getSourceRange();
1513 return true;
1514 }
1515
John McCall5b0829a2010-02-10 09:31:12 +00001516 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001517 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1518 Paths.front(),
1519 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001520
Anders Carlssond7923c62009-08-22 23:33:40 +00001521 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001522 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001523 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001524 return false;
1525}
1526
Douglas Gregor9a657932008-10-21 23:43:52 +00001527/// IsQualificationConversion - Determines whether the conversion from
1528/// an rvalue of type FromType to ToType is a qualification conversion
1529/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001530bool
1531Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001532 FromType = Context.getCanonicalType(FromType);
1533 ToType = Context.getCanonicalType(ToType);
1534
1535 // If FromType and ToType are the same type, this is not a
1536 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001537 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001538 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001539
Douglas Gregor9a657932008-10-21 23:43:52 +00001540 // (C++ 4.4p4):
1541 // A conversion can add cv-qualifiers at levels other than the first
1542 // in multi-level pointers, subject to the following rules: [...]
1543 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001544 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001545 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001546 // Within each iteration of the loop, we check the qualifiers to
1547 // determine if this still looks like a qualification
1548 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001549 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001550 // until there are no more pointers or pointers-to-members left to
1551 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001552 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001553
1554 // -- for every j > 0, if const is in cv 1,j then const is in cv
1555 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001556 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001557 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001558
Douglas Gregor9a657932008-10-21 23:43:52 +00001559 // -- if the cv 1,j and cv 2,j are different, then const is in
1560 // every cv for 0 < k < j.
1561 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001562 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001563 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001564
Douglas Gregor9a657932008-10-21 23:43:52 +00001565 // Keep track of whether all prior cv-qualifiers in the "to" type
1566 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001567 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001568 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001569 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001570
1571 // We are left with FromType and ToType being the pointee types
1572 // after unwrapping the original FromType and ToType the same number
1573 // of types. If we unwrapped any pointers, and if FromType and
1574 // ToType have the same unqualified type (since we checked
1575 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001576 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001577}
1578
Douglas Gregor576e98c2009-01-30 23:27:23 +00001579/// Determines whether there is a user-defined conversion sequence
1580/// (C++ [over.ics.user]) that converts expression From to the type
1581/// ToType. If such a conversion exists, User will contain the
1582/// user-defined conversion sequence that performs such a conversion
1583/// and this routine will return true. Otherwise, this routine returns
1584/// false and User is unspecified.
1585///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001586/// \param AllowExplicit true if the conversion should consider C++0x
1587/// "explicit" conversion functions as well as non-explicit conversion
1588/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001589OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1590 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001591 OverloadCandidateSet& CandidateSet,
1592 bool AllowExplicit) {
1593 // Whether we will only visit constructors.
1594 bool ConstructorsOnly = false;
1595
1596 // If the type we are conversion to is a class type, enumerate its
1597 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001598 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001599 // C++ [over.match.ctor]p1:
1600 // When objects of class type are direct-initialized (8.5), or
1601 // copy-initialized from an expression of the same or a
1602 // derived class type (8.5), overload resolution selects the
1603 // constructor. [...] For copy-initialization, the candidate
1604 // functions are all the converting constructors (12.3.1) of
1605 // that class. The argument list is the expression-list within
1606 // the parentheses of the initializer.
1607 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1608 (From->getType()->getAs<RecordType>() &&
1609 IsDerivedFrom(From->getType(), ToType)))
1610 ConstructorsOnly = true;
1611
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001612 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1613 // We're not going to find any constructors.
1614 } else if (CXXRecordDecl *ToRecordDecl
1615 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001616 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001617 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001618 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001619 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001620 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001621 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001622 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001623 NamedDecl *D = *Con;
1624 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1625
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001626 // Find the constructor (which may be a template).
1627 CXXConstructorDecl *Constructor = 0;
1628 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001629 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001630 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001631 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001632 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1633 else
John McCalla0296f72010-03-19 07:35:19 +00001634 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001635
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001636 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001637 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001638 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001639 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001640 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001641 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001642 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001643 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001644 // Allow one user-defined conversion when user specifies a
1645 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001646 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001647 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001648 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001649 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001650 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001651 }
1652 }
1653
Douglas Gregor5ab11652010-04-17 22:01:05 +00001654 // Enumerate conversion functions, if we're allowed to.
1655 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001656 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001657 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001658 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001659 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001660 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001661 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001662 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1663 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001664 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001665 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001666 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001667 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001668 DeclAccessPair FoundDecl = I.getPair();
1669 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001670 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1671 if (isa<UsingShadowDecl>(D))
1672 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1673
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001674 CXXConversionDecl *Conv;
1675 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001676 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1677 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001678 else
John McCallda4458e2010-03-31 01:36:47 +00001679 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001680
1681 if (AllowExplicit || !Conv->isExplicit()) {
1682 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001683 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001684 ActingContext, From, ToType,
1685 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001686 else
John McCalla0296f72010-03-19 07:35:19 +00001687 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001688 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001689 }
1690 }
1691 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001692 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001693
1694 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001695 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001696 case OR_Success:
1697 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001698 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001699 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1700 // C++ [over.ics.user]p1:
1701 // If the user-defined conversion is specified by a
1702 // constructor (12.3.1), the initial standard conversion
1703 // sequence converts the source type to the type required by
1704 // the argument of the constructor.
1705 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001706 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001707 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001708 User.EllipsisConversion = true;
1709 else {
1710 User.Before = Best->Conversions[0].Standard;
1711 User.EllipsisConversion = false;
1712 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001713 User.ConversionFunction = Constructor;
1714 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001715 User.After.setFromType(
1716 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001717 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001718 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001719 } else if (CXXConversionDecl *Conversion
1720 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1721 // C++ [over.ics.user]p1:
1722 //
1723 // [...] If the user-defined conversion is specified by a
1724 // conversion function (12.3.2), the initial standard
1725 // conversion sequence converts the source type to the
1726 // implicit object parameter of the conversion function.
1727 User.Before = Best->Conversions[0].Standard;
1728 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001729 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001730
1731 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001732 // The second standard conversion sequence converts the
1733 // result of the user-defined conversion to the target type
1734 // for the sequence. Since an implicit conversion sequence
1735 // is an initialization, the special rules for
1736 // initialization by user-defined conversion apply when
1737 // selecting the best user-defined conversion for a
1738 // user-defined conversion sequence (see 13.3.3 and
1739 // 13.3.3.1).
1740 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001741 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001742 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001743 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001744 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001745 }
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001747 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001748 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001749 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001750 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001751 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001752
1753 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001754 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001755 }
1756
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001757 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001758}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001759
1760bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001761Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001762 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001763 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001764 OverloadingResult OvResult =
1765 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001766 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001767 if (OvResult == OR_Ambiguous)
1768 Diag(From->getSourceRange().getBegin(),
1769 diag::err_typecheck_ambiguous_condition)
1770 << From->getType() << ToType << From->getSourceRange();
1771 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1772 Diag(From->getSourceRange().getBegin(),
1773 diag::err_typecheck_nonviable_condition)
1774 << From->getType() << ToType << From->getSourceRange();
1775 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001776 return false;
John McCallad907772010-01-12 07:18:19 +00001777 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001778 return true;
1779}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001780
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001781/// CompareImplicitConversionSequences - Compare two implicit
1782/// conversion sequences to determine whether one is better than the
1783/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001784ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001785Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1786 const ImplicitConversionSequence& ICS2)
1787{
1788 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1789 // conversion sequences (as defined in 13.3.3.1)
1790 // -- a standard conversion sequence (13.3.3.1.1) is a better
1791 // conversion sequence than a user-defined conversion sequence or
1792 // an ellipsis conversion sequence, and
1793 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1794 // conversion sequence than an ellipsis conversion sequence
1795 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001796 //
John McCall0d1da222010-01-12 00:44:57 +00001797 // C++0x [over.best.ics]p10:
1798 // For the purpose of ranking implicit conversion sequences as
1799 // described in 13.3.3.2, the ambiguous conversion sequence is
1800 // treated as a user-defined sequence that is indistinguishable
1801 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00001802 if (ICS1.getKindRank() < ICS2.getKindRank())
1803 return ImplicitConversionSequence::Better;
1804 else if (ICS2.getKindRank() < ICS1.getKindRank())
1805 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001806
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00001807 // The following checks require both conversion sequences to be of
1808 // the same kind.
1809 if (ICS1.getKind() != ICS2.getKind())
1810 return ImplicitConversionSequence::Indistinguishable;
1811
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001812 // Two implicit conversion sequences of the same form are
1813 // indistinguishable conversion sequences unless one of the
1814 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001815 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001816 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001817 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001818 // User-defined conversion sequence U1 is a better conversion
1819 // sequence than another user-defined conversion sequence U2 if
1820 // they contain the same user-defined conversion function or
1821 // constructor and if the second standard conversion sequence of
1822 // U1 is better than the second standard conversion sequence of
1823 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001824 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 ICS2.UserDefined.ConversionFunction)
1826 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1827 ICS2.UserDefined.After);
1828 }
1829
1830 return ImplicitConversionSequence::Indistinguishable;
1831}
1832
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001833// Per 13.3.3.2p3, compare the given standard conversion sequences to
1834// determine if one is a proper subset of the other.
1835static ImplicitConversionSequence::CompareKind
1836compareStandardConversionSubsets(ASTContext &Context,
1837 const StandardConversionSequence& SCS1,
1838 const StandardConversionSequence& SCS2) {
1839 ImplicitConversionSequence::CompareKind Result
1840 = ImplicitConversionSequence::Indistinguishable;
1841
1842 if (SCS1.Second != SCS2.Second) {
1843 if (SCS1.Second == ICK_Identity)
1844 Result = ImplicitConversionSequence::Better;
1845 else if (SCS2.Second == ICK_Identity)
1846 Result = ImplicitConversionSequence::Worse;
1847 else
1848 return ImplicitConversionSequence::Indistinguishable;
1849 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1850 return ImplicitConversionSequence::Indistinguishable;
1851
1852 if (SCS1.Third == SCS2.Third) {
1853 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1854 : ImplicitConversionSequence::Indistinguishable;
1855 }
1856
1857 if (SCS1.Third == ICK_Identity)
1858 return Result == ImplicitConversionSequence::Worse
1859 ? ImplicitConversionSequence::Indistinguishable
1860 : ImplicitConversionSequence::Better;
1861
1862 if (SCS2.Third == ICK_Identity)
1863 return Result == ImplicitConversionSequence::Better
1864 ? ImplicitConversionSequence::Indistinguishable
1865 : ImplicitConversionSequence::Worse;
1866
1867 return ImplicitConversionSequence::Indistinguishable;
1868}
1869
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001870/// CompareStandardConversionSequences - Compare two standard
1871/// conversion sequences to determine whether one is better than the
1872/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001873ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001874Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1875 const StandardConversionSequence& SCS2)
1876{
1877 // Standard conversion sequence S1 is a better conversion sequence
1878 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1879
1880 // -- S1 is a proper subsequence of S2 (comparing the conversion
1881 // sequences in the canonical form defined by 13.3.3.1.1,
1882 // excluding any Lvalue Transformation; the identity conversion
1883 // sequence is considered to be a subsequence of any
1884 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001885 if (ImplicitConversionSequence::CompareKind CK
1886 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1887 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888
1889 // -- the rank of S1 is better than the rank of S2 (by the rules
1890 // defined below), or, if not that,
1891 ImplicitConversionRank Rank1 = SCS1.getRank();
1892 ImplicitConversionRank Rank2 = SCS2.getRank();
1893 if (Rank1 < Rank2)
1894 return ImplicitConversionSequence::Better;
1895 else if (Rank2 < Rank1)
1896 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001897
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001898 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1899 // are indistinguishable unless one of the following rules
1900 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001901
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001902 // A conversion that is not a conversion of a pointer, or
1903 // pointer to member, to bool is better than another conversion
1904 // that is such a conversion.
1905 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1906 return SCS2.isPointerConversionToBool()
1907 ? ImplicitConversionSequence::Better
1908 : ImplicitConversionSequence::Worse;
1909
Douglas Gregor5c407d92008-10-23 00:40:37 +00001910 // C++ [over.ics.rank]p4b2:
1911 //
1912 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001913 // conversion of B* to A* is better than conversion of B* to
1914 // void*, and conversion of A* to void* is better than conversion
1915 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001916 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001917 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001918 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001919 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001920 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1921 // Exactly one of the conversion sequences is a conversion to
1922 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001923 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1924 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001925 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1926 // Neither conversion sequence converts to a void pointer; compare
1927 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001928 if (ImplicitConversionSequence::CompareKind DerivedCK
1929 = CompareDerivedToBaseConversions(SCS1, SCS2))
1930 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001931 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1932 // Both conversion sequences are conversions to void
1933 // pointers. Compare the source types to determine if there's an
1934 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001935 QualType FromType1 = SCS1.getFromType();
1936 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001937
1938 // Adjust the types we're converting from via the array-to-pointer
1939 // conversion, if we need to.
1940 if (SCS1.First == ICK_Array_To_Pointer)
1941 FromType1 = Context.getArrayDecayedType(FromType1);
1942 if (SCS2.First == ICK_Array_To_Pointer)
1943 FromType2 = Context.getArrayDecayedType(FromType2);
1944
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001945 QualType FromPointee1
1946 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1947 QualType FromPointee2
1948 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001949
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001950 if (IsDerivedFrom(FromPointee2, FromPointee1))
1951 return ImplicitConversionSequence::Better;
1952 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1953 return ImplicitConversionSequence::Worse;
1954
1955 // Objective-C++: If one interface is more specific than the
1956 // other, it is the better one.
1957 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1958 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1959 if (FromIface1 && FromIface1) {
1960 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1961 return ImplicitConversionSequence::Better;
1962 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1963 return ImplicitConversionSequence::Worse;
1964 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001965 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001966
1967 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1968 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001969 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001970 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001971 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001972
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001973 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001974 // C++0x [over.ics.rank]p3b4:
1975 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1976 // implicit object parameter of a non-static member function declared
1977 // without a ref-qualifier, and S1 binds an rvalue reference to an
1978 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001979 // FIXME: We don't know if we're dealing with the implicit object parameter,
1980 // or if the member function in this case has a ref qualifier.
1981 // (Of course, we don't have ref qualifiers yet.)
1982 if (SCS1.RRefBinding != SCS2.RRefBinding)
1983 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1984 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001985
1986 // C++ [over.ics.rank]p3b4:
1987 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1988 // which the references refer are the same type except for
1989 // top-level cv-qualifiers, and the type to which the reference
1990 // initialized by S2 refers is more cv-qualified than the type
1991 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001992 QualType T1 = SCS1.getToType(2);
1993 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001994 T1 = Context.getCanonicalType(T1);
1995 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001996 Qualifiers T1Quals, T2Quals;
1997 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1998 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1999 if (UnqualT1 == UnqualT2) {
2000 // If the type is an array type, promote the element qualifiers to the type
2001 // for comparison.
2002 if (isa<ArrayType>(T1) && T1Quals)
2003 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2004 if (isa<ArrayType>(T2) && T2Quals)
2005 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002006 if (T2.isMoreQualifiedThan(T1))
2007 return ImplicitConversionSequence::Better;
2008 else if (T1.isMoreQualifiedThan(T2))
2009 return ImplicitConversionSequence::Worse;
2010 }
2011 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002012
2013 return ImplicitConversionSequence::Indistinguishable;
2014}
2015
2016/// CompareQualificationConversions - Compares two standard conversion
2017/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002018/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2019ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002020Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002021 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002022 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002023 // -- S1 and S2 differ only in their qualification conversion and
2024 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2025 // cv-qualification signature of type T1 is a proper subset of
2026 // the cv-qualification signature of type T2, and S1 is not the
2027 // deprecated string literal array-to-pointer conversion (4.2).
2028 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2029 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2030 return ImplicitConversionSequence::Indistinguishable;
2031
2032 // FIXME: the example in the standard doesn't use a qualification
2033 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002034 QualType T1 = SCS1.getToType(2);
2035 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002036 T1 = Context.getCanonicalType(T1);
2037 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002038 Qualifiers T1Quals, T2Quals;
2039 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2040 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002041
2042 // If the types are the same, we won't learn anything by unwrapped
2043 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002044 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002045 return ImplicitConversionSequence::Indistinguishable;
2046
Chandler Carruth607f38e2009-12-29 07:16:59 +00002047 // If the type is an array type, promote the element qualifiers to the type
2048 // for comparison.
2049 if (isa<ArrayType>(T1) && T1Quals)
2050 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2051 if (isa<ArrayType>(T2) && T2Quals)
2052 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2053
Mike Stump11289f42009-09-09 15:08:12 +00002054 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002055 = ImplicitConversionSequence::Indistinguishable;
2056 while (UnwrapSimilarPointerTypes(T1, T2)) {
2057 // Within each iteration of the loop, we check the qualifiers to
2058 // determine if this still looks like a qualification
2059 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002060 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002061 // until there are no more pointers or pointers-to-members left
2062 // to unwrap. This essentially mimics what
2063 // IsQualificationConversion does, but here we're checking for a
2064 // strict subset of qualifiers.
2065 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2066 // The qualifiers are the same, so this doesn't tell us anything
2067 // about how the sequences rank.
2068 ;
2069 else if (T2.isMoreQualifiedThan(T1)) {
2070 // T1 has fewer qualifiers, so it could be the better sequence.
2071 if (Result == ImplicitConversionSequence::Worse)
2072 // Neither has qualifiers that are a subset of the other's
2073 // qualifiers.
2074 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002075
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002076 Result = ImplicitConversionSequence::Better;
2077 } else if (T1.isMoreQualifiedThan(T2)) {
2078 // T2 has fewer qualifiers, so it could be the better sequence.
2079 if (Result == ImplicitConversionSequence::Better)
2080 // Neither has qualifiers that are a subset of the other's
2081 // qualifiers.
2082 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002083
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002084 Result = ImplicitConversionSequence::Worse;
2085 } else {
2086 // Qualifiers are disjoint.
2087 return ImplicitConversionSequence::Indistinguishable;
2088 }
2089
2090 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002091 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002092 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002093 }
2094
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002095 // Check that the winning standard conversion sequence isn't using
2096 // the deprecated string literal array to pointer conversion.
2097 switch (Result) {
2098 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002099 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002100 Result = ImplicitConversionSequence::Indistinguishable;
2101 break;
2102
2103 case ImplicitConversionSequence::Indistinguishable:
2104 break;
2105
2106 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002107 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002108 Result = ImplicitConversionSequence::Indistinguishable;
2109 break;
2110 }
2111
2112 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002113}
2114
Douglas Gregor5c407d92008-10-23 00:40:37 +00002115/// CompareDerivedToBaseConversions - Compares two standard conversion
2116/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002117/// various kinds of derived-to-base conversions (C++
2118/// [over.ics.rank]p4b3). As part of these checks, we also look at
2119/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002120ImplicitConversionSequence::CompareKind
2121Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2122 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002123 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002124 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002125 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002126 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002127
2128 // Adjust the types we're converting from via the array-to-pointer
2129 // conversion, if we need to.
2130 if (SCS1.First == ICK_Array_To_Pointer)
2131 FromType1 = Context.getArrayDecayedType(FromType1);
2132 if (SCS2.First == ICK_Array_To_Pointer)
2133 FromType2 = Context.getArrayDecayedType(FromType2);
2134
2135 // Canonicalize all of the types.
2136 FromType1 = Context.getCanonicalType(FromType1);
2137 ToType1 = Context.getCanonicalType(ToType1);
2138 FromType2 = Context.getCanonicalType(FromType2);
2139 ToType2 = Context.getCanonicalType(ToType2);
2140
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002141 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002142 //
2143 // If class B is derived directly or indirectly from class A and
2144 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002145 //
2146 // For Objective-C, we let A, B, and C also be Objective-C
2147 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002148
2149 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002150 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002151 SCS2.Second == ICK_Pointer_Conversion &&
2152 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2153 FromType1->isPointerType() && FromType2->isPointerType() &&
2154 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002155 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002156 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002157 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002158 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002159 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002160 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002161 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002162 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002163
John McCall9dd450b2009-09-21 23:43:11 +00002164 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2165 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2166 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2167 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002168
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002169 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002170 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2171 if (IsDerivedFrom(ToPointee1, ToPointee2))
2172 return ImplicitConversionSequence::Better;
2173 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2174 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002175
2176 if (ToIface1 && ToIface2) {
2177 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2178 return ImplicitConversionSequence::Better;
2179 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2180 return ImplicitConversionSequence::Worse;
2181 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002182 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002183
2184 // -- conversion of B* to A* is better than conversion of C* to A*,
2185 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2186 if (IsDerivedFrom(FromPointee2, FromPointee1))
2187 return ImplicitConversionSequence::Better;
2188 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2189 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002190
Douglas Gregor237f96c2008-11-26 23:31:11 +00002191 if (FromIface1 && FromIface2) {
2192 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2193 return ImplicitConversionSequence::Better;
2194 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2195 return ImplicitConversionSequence::Worse;
2196 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002197 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002198 }
2199
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002200 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002201 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2202 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2203 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2204 const MemberPointerType * FromMemPointer1 =
2205 FromType1->getAs<MemberPointerType>();
2206 const MemberPointerType * ToMemPointer1 =
2207 ToType1->getAs<MemberPointerType>();
2208 const MemberPointerType * FromMemPointer2 =
2209 FromType2->getAs<MemberPointerType>();
2210 const MemberPointerType * ToMemPointer2 =
2211 ToType2->getAs<MemberPointerType>();
2212 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2213 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2214 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2215 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2216 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2217 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2218 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2219 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002220 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002221 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2222 if (IsDerivedFrom(ToPointee1, ToPointee2))
2223 return ImplicitConversionSequence::Worse;
2224 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2225 return ImplicitConversionSequence::Better;
2226 }
2227 // conversion of B::* to C::* is better than conversion of A::* to C::*
2228 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2229 if (IsDerivedFrom(FromPointee1, FromPointee2))
2230 return ImplicitConversionSequence::Better;
2231 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2232 return ImplicitConversionSequence::Worse;
2233 }
2234 }
2235
Douglas Gregor5ab11652010-04-17 22:01:05 +00002236 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002237 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002238 // -- binding of an expression of type C to a reference of type
2239 // B& is better than binding an expression of type C to a
2240 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002241 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2242 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002243 if (IsDerivedFrom(ToType1, ToType2))
2244 return ImplicitConversionSequence::Better;
2245 else if (IsDerivedFrom(ToType2, ToType1))
2246 return ImplicitConversionSequence::Worse;
2247 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002248
Douglas Gregor2fe98832008-11-03 19:09:14 +00002249 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002250 // -- binding of an expression of type B to a reference of type
2251 // A& is better than binding an expression of type C to a
2252 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002253 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2254 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002255 if (IsDerivedFrom(FromType2, FromType1))
2256 return ImplicitConversionSequence::Better;
2257 else if (IsDerivedFrom(FromType1, FromType2))
2258 return ImplicitConversionSequence::Worse;
2259 }
2260 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002261
Douglas Gregor5c407d92008-10-23 00:40:37 +00002262 return ImplicitConversionSequence::Indistinguishable;
2263}
2264
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002265/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2266/// determine whether they are reference-related,
2267/// reference-compatible, reference-compatible with added
2268/// qualification, or incompatible, for use in C++ initialization by
2269/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2270/// type, and the first type (T1) is the pointee type of the reference
2271/// type being initialized.
2272Sema::ReferenceCompareResult
2273Sema::CompareReferenceRelationship(SourceLocation Loc,
2274 QualType OrigT1, QualType OrigT2,
2275 bool& DerivedToBase) {
2276 assert(!OrigT1->isReferenceType() &&
2277 "T1 must be the pointee type of the reference type");
2278 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2279
2280 QualType T1 = Context.getCanonicalType(OrigT1);
2281 QualType T2 = Context.getCanonicalType(OrigT2);
2282 Qualifiers T1Quals, T2Quals;
2283 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2284 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2285
2286 // C++ [dcl.init.ref]p4:
2287 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2288 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2289 // T1 is a base class of T2.
2290 if (UnqualT1 == UnqualT2)
2291 DerivedToBase = false;
2292 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
2293 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
2294 IsDerivedFrom(UnqualT2, UnqualT1))
2295 DerivedToBase = true;
2296 else
2297 return Ref_Incompatible;
2298
2299 // At this point, we know that T1 and T2 are reference-related (at
2300 // least).
2301
2302 // If the type is an array type, promote the element qualifiers to the type
2303 // for comparison.
2304 if (isa<ArrayType>(T1) && T1Quals)
2305 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2306 if (isa<ArrayType>(T2) && T2Quals)
2307 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2308
2309 // C++ [dcl.init.ref]p4:
2310 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2311 // reference-related to T2 and cv1 is the same cv-qualification
2312 // as, or greater cv-qualification than, cv2. For purposes of
2313 // overload resolution, cases for which cv1 is greater
2314 // cv-qualification than cv2 are identified as
2315 // reference-compatible with added qualification (see 13.3.3.2).
2316 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2317 return Ref_Compatible;
2318 else if (T1.isMoreQualifiedThan(T2))
2319 return Ref_Compatible_With_Added_Qualification;
2320 else
2321 return Ref_Related;
2322}
2323
2324/// \brief Compute an implicit conversion sequence for reference
2325/// initialization.
2326static ImplicitConversionSequence
2327TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2328 SourceLocation DeclLoc,
2329 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002330 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002331 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2332
2333 // Most paths end in a failed conversion.
2334 ImplicitConversionSequence ICS;
2335 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2336
2337 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2338 QualType T2 = Init->getType();
2339
2340 // If the initializer is the address of an overloaded function, try
2341 // to resolve the overloaded function. If all goes well, T2 is the
2342 // type of the resulting function.
2343 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2344 DeclAccessPair Found;
2345 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2346 false, Found))
2347 T2 = Fn->getType();
2348 }
2349
2350 // Compute some basic properties of the types and the initializer.
2351 bool isRValRef = DeclType->isRValueReferenceType();
2352 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002353 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002354 Sema::ReferenceCompareResult RefRelationship
2355 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2356
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002357
2358 // C++ [over.ics.ref]p3:
2359 // Except for an implicit object parameter, for which see 13.3.1,
2360 // a standard conversion sequence cannot be formed if it requires
2361 // binding an lvalue reference to non-const to an rvalue or
2362 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002363 //
2364 // FIXME: DPG doesn't trust this code. It seems far too early to
2365 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002366 if (isRValRef && InitLvalue == Expr::LV_Valid)
2367 return ICS;
2368
Douglas Gregor870f3742010-04-18 09:22:00 +00002369 // C++0x [dcl.init.ref]p16:
2370 // A reference to type "cv1 T1" is initialized by an expression
2371 // of type "cv2 T2" as follows:
2372
2373 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002374 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2375 // reference-compatible with "cv2 T2," or
2376 //
2377 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2378 if (InitLvalue == Expr::LV_Valid &&
2379 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2380 // C++ [over.ics.ref]p1:
2381 // When a parameter of reference type binds directly (8.5.3)
2382 // to an argument expression, the implicit conversion sequence
2383 // is the identity conversion, unless the argument expression
2384 // has a type that is a derived class of the parameter type,
2385 // in which case the implicit conversion sequence is a
2386 // derived-to-base Conversion (13.3.3.1).
2387 ICS.setStandard();
2388 ICS.Standard.First = ICK_Identity;
2389 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2390 ICS.Standard.Third = ICK_Identity;
2391 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2392 ICS.Standard.setToType(0, T2);
2393 ICS.Standard.setToType(1, T1);
2394 ICS.Standard.setToType(2, T1);
2395 ICS.Standard.ReferenceBinding = true;
2396 ICS.Standard.DirectBinding = true;
2397 ICS.Standard.RRefBinding = false;
2398 ICS.Standard.CopyConstructor = 0;
2399
2400 // Nothing more to do: the inaccessibility/ambiguity check for
2401 // derived-to-base conversions is suppressed when we're
2402 // computing the implicit conversion sequence (C++
2403 // [over.best.ics]p2).
2404 return ICS;
2405 }
2406
2407 // -- has a class type (i.e., T2 is a class type), where T1 is
2408 // not reference-related to T2, and can be implicitly
2409 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2410 // is reference-compatible with "cv3 T3" 92) (this
2411 // conversion is selected by enumerating the applicable
2412 // conversion functions (13.3.1.6) and choosing the best
2413 // one through overload resolution (13.3)),
2414 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2415 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2416 RefRelationship == Sema::Ref_Incompatible) {
2417 CXXRecordDecl *T2RecordDecl
2418 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2419
2420 OverloadCandidateSet CandidateSet(DeclLoc);
2421 const UnresolvedSetImpl *Conversions
2422 = T2RecordDecl->getVisibleConversionFunctions();
2423 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2424 E = Conversions->end(); I != E; ++I) {
2425 NamedDecl *D = *I;
2426 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2427 if (isa<UsingShadowDecl>(D))
2428 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2429
2430 FunctionTemplateDecl *ConvTemplate
2431 = dyn_cast<FunctionTemplateDecl>(D);
2432 CXXConversionDecl *Conv;
2433 if (ConvTemplate)
2434 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2435 else
2436 Conv = cast<CXXConversionDecl>(D);
2437
2438 // If the conversion function doesn't return a reference type,
2439 // it can't be considered for this conversion.
2440 if (Conv->getConversionType()->isLValueReferenceType() &&
2441 (AllowExplicit || !Conv->isExplicit())) {
2442 if (ConvTemplate)
2443 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2444 Init, DeclType, CandidateSet);
2445 else
2446 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2447 DeclType, CandidateSet);
2448 }
2449 }
2450
2451 OverloadCandidateSet::iterator Best;
2452 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2453 case OR_Success:
2454 // C++ [over.ics.ref]p1:
2455 //
2456 // [...] If the parameter binds directly to the result of
2457 // applying a conversion function to the argument
2458 // expression, the implicit conversion sequence is a
2459 // user-defined conversion sequence (13.3.3.1.2), with the
2460 // second standard conversion sequence either an identity
2461 // conversion or, if the conversion function returns an
2462 // entity of a type that is a derived class of the parameter
2463 // type, a derived-to-base Conversion.
2464 if (!Best->FinalConversion.DirectBinding)
2465 break;
2466
2467 ICS.setUserDefined();
2468 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2469 ICS.UserDefined.After = Best->FinalConversion;
2470 ICS.UserDefined.ConversionFunction = Best->Function;
2471 ICS.UserDefined.EllipsisConversion = false;
2472 assert(ICS.UserDefined.After.ReferenceBinding &&
2473 ICS.UserDefined.After.DirectBinding &&
2474 "Expected a direct reference binding!");
2475 return ICS;
2476
2477 case OR_Ambiguous:
2478 ICS.setAmbiguous();
2479 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2480 Cand != CandidateSet.end(); ++Cand)
2481 if (Cand->Viable)
2482 ICS.Ambiguous.addConversion(Cand->Function);
2483 return ICS;
2484
2485 case OR_No_Viable_Function:
2486 case OR_Deleted:
2487 // There was no suitable conversion, or we found a deleted
2488 // conversion; continue with other checks.
2489 break;
2490 }
2491 }
2492
2493 // -- Otherwise, the reference shall be to a non-volatile const
2494 // type (i.e., cv1 shall be const), or the reference shall be an
2495 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002496 //
2497 // We actually handle one oddity of C++ [over.ics.ref] at this
2498 // point, which is that, due to p2 (which short-circuits reference
2499 // binding by only attempting a simple conversion for non-direct
2500 // bindings) and p3's strange wording, we allow a const volatile
2501 // reference to bind to an rvalue. Hence the check for the presence
2502 // of "const" rather than checking for "const" being the only
2503 // qualifier.
2504 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002505 return ICS;
2506
Douglas Gregorf93df192010-04-18 08:46:23 +00002507 // -- if T2 is a class type and
2508 // -- the initializer expression is an rvalue and "cv1 T1"
2509 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002510 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002511 // -- T1 is not reference-related to T2 and the initializer
2512 // expression can be implicitly converted to an rvalue
2513 // of type "cv3 T3" (this conversion is selected by
2514 // enumerating the applicable conversion functions
2515 // (13.3.1.6) and choosing the best one through overload
2516 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002517 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002518 // then the reference is bound to the initializer
2519 // expression rvalue in the first case and to the object
2520 // that is the result of the conversion in the second case
2521 // (or, in either case, to the appropriate base class
2522 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002523 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002524 // We're only checking the first case here, which is a direct
2525 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002526 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2527 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2528 ICS.setStandard();
2529 ICS.Standard.First = ICK_Identity;
2530 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2531 ICS.Standard.Third = ICK_Identity;
2532 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2533 ICS.Standard.setToType(0, T2);
2534 ICS.Standard.setToType(1, T1);
2535 ICS.Standard.setToType(2, T1);
2536 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002537 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002538 ICS.Standard.RRefBinding = isRValRef;
2539 ICS.Standard.CopyConstructor = 0;
2540 return ICS;
2541 }
2542
2543 // -- Otherwise, a temporary of type "cv1 T1" is created and
2544 // initialized from the initializer expression using the
2545 // rules for a non-reference copy initialization (8.5). The
2546 // reference is then bound to the temporary. If T1 is
2547 // reference-related to T2, cv1 must be the same
2548 // cv-qualification as, or greater cv-qualification than,
2549 // cv2; otherwise, the program is ill-formed.
2550 if (RefRelationship == Sema::Ref_Related) {
2551 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2552 // we would be reference-compatible or reference-compatible with
2553 // added qualification. But that wasn't the case, so the reference
2554 // initialization fails.
2555 return ICS;
2556 }
2557
2558 // If at least one of the types is a class type, the types are not
2559 // related, and we aren't allowed any user conversions, the
2560 // reference binding fails. This case is important for breaking
2561 // recursion, since TryImplicitConversion below will attempt to
2562 // create a temporary through the use of a copy constructor.
2563 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2564 (T1->isRecordType() || T2->isRecordType()))
2565 return ICS;
2566
2567 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002568 // When a parameter of reference type is not bound directly to
2569 // an argument expression, the conversion sequence is the one
2570 // required to convert the argument expression to the
2571 // underlying type of the reference according to
2572 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2573 // to copy-initializing a temporary of the underlying type with
2574 // the argument expression. Any difference in top-level
2575 // cv-qualification is subsumed by the initialization itself
2576 // and does not constitute a conversion.
2577 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2578 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002579 /*InOverloadResolution=*/false);
2580
2581 // Of course, that's still a reference binding.
2582 if (ICS.isStandard()) {
2583 ICS.Standard.ReferenceBinding = true;
2584 ICS.Standard.RRefBinding = isRValRef;
2585 } else if (ICS.isUserDefined()) {
2586 ICS.UserDefined.After.ReferenceBinding = true;
2587 ICS.UserDefined.After.RRefBinding = isRValRef;
2588 }
2589 return ICS;
2590}
2591
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002592/// TryCopyInitialization - Try to copy-initialize a value of type
2593/// ToType from the expression From. Return the implicit conversion
2594/// sequence required to pass this argument, which may be a bad
2595/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002596/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002597/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002598static ImplicitConversionSequence
2599TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002600 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002601 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002602 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002603 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002604 /*FIXME:*/From->getLocStart(),
2605 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002606 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002607
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002608 return S.TryImplicitConversion(From, ToType,
2609 SuppressUserConversions,
2610 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002611 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002612}
2613
Douglas Gregor436424c2008-11-18 23:14:02 +00002614/// TryObjectArgumentInitialization - Try to initialize the object
2615/// parameter of the given member function (@c Method) from the
2616/// expression @p From.
2617ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002618Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002619 CXXMethodDecl *Method,
2620 CXXRecordDecl *ActingContext) {
2621 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002622 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2623 // const volatile object.
2624 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2625 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2626 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002627
2628 // Set up the conversion sequence as a "bad" conversion, to allow us
2629 // to exit early.
2630 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002631
2632 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002633 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002634 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002635 FromType = PT->getPointeeType();
2636
2637 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002638
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002639 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002640 // where X is the class of which the function is a member
2641 // (C++ [over.match.funcs]p4). However, when finding an implicit
2642 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002643 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002644 // (C++ [over.match.funcs]p5). We perform a simplified version of
2645 // reference binding here, that allows class rvalues to bind to
2646 // non-constant references.
2647
2648 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2649 // with the implicit object parameter (C++ [over.match.funcs]p5).
2650 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002651 if (ImplicitParamType.getCVRQualifiers()
2652 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002653 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002654 ICS.setBad(BadConversionSequence::bad_qualifiers,
2655 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002656 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002657 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002658
2659 // Check that we have either the same type or a derived type. It
2660 // affects the conversion rank.
2661 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002662 ImplicitConversionKind SecondKind;
2663 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2664 SecondKind = ICK_Identity;
2665 } else if (IsDerivedFrom(FromType, ClassType))
2666 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002667 else {
John McCall65eb8792010-02-25 01:37:24 +00002668 ICS.setBad(BadConversionSequence::unrelated_class,
2669 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002670 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002671 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002672
2673 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002674 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002675 ICS.Standard.setAsIdentityConversion();
2676 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002677 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002678 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002679 ICS.Standard.ReferenceBinding = true;
2680 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002681 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002682 return ICS;
2683}
2684
2685/// PerformObjectArgumentInitialization - Perform initialization of
2686/// the implicit object parameter for the given Method with the given
2687/// expression.
2688bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002689Sema::PerformObjectArgumentInitialization(Expr *&From,
2690 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002691 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002692 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002693 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002694 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002695 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002696
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002697 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002698 FromRecordType = PT->getPointeeType();
2699 DestType = Method->getThisType(Context);
2700 } else {
2701 FromRecordType = From->getType();
2702 DestType = ImplicitParamRecordType;
2703 }
2704
John McCall6e9f8f62009-12-03 04:06:58 +00002705 // Note that we always use the true parent context when performing
2706 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002707 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002708 = TryObjectArgumentInitialization(From->getType(), Method,
2709 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002710 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002711 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002712 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002713 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002714
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002715 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002716 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002717
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002718 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002719 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2720 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002721 return false;
2722}
2723
Douglas Gregor5fb53972009-01-14 15:45:31 +00002724/// TryContextuallyConvertToBool - Attempt to contextually convert the
2725/// expression From to bool (C++0x [conv]p3).
2726ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002727 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002728 // FIXME: Are these flags correct?
2729 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002730 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002731 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002732}
2733
2734/// PerformContextuallyConvertToBool - Perform a contextual conversion
2735/// of the expression From to bool (C++0x [conv]p3).
2736bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2737 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002738 if (!ICS.isBad())
2739 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002740
Fariborz Jahanian76197412009-11-18 18:26:29 +00002741 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002742 return Diag(From->getSourceRange().getBegin(),
2743 diag::err_typecheck_bool_condition)
2744 << From->getType() << From->getSourceRange();
2745 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002746}
2747
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002748/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002749/// candidate functions, using the given function call arguments. If
2750/// @p SuppressUserConversions, then don't allow user-defined
2751/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002752///
2753/// \para PartialOverloading true if we are performing "partial" overloading
2754/// based on an incomplete set of function arguments. This feature is used by
2755/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002756void
2757Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002758 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002759 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002760 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002761 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002762 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002763 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002764 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002765 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002766 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002767 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002768
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002769 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002770 if (!isa<CXXConstructorDecl>(Method)) {
2771 // If we get here, it's because we're calling a member function
2772 // that is named without a member access expression (e.g.,
2773 // "this->f") that was either written explicitly or created
2774 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002775 // function, e.g., X::f(). We use an empty type for the implied
2776 // object argument (C++ [over.call.func]p3), and the acting context
2777 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002778 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002779 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002780 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002781 return;
2782 }
2783 // We treat a constructor like a non-member function, since its object
2784 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002785 }
2786
Douglas Gregorff7028a2009-11-13 23:59:09 +00002787 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002788 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002789
Douglas Gregor27381f32009-11-23 12:27:39 +00002790 // Overload resolution is always an unevaluated context.
2791 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2792
Douglas Gregorffe14e32009-11-14 01:20:54 +00002793 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2794 // C++ [class.copy]p3:
2795 // A member function template is never instantiated to perform the copy
2796 // of a class object to an object of its class type.
2797 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2798 if (NumArgs == 1 &&
2799 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002800 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2801 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002802 return;
2803 }
2804
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002805 // Add this candidate
2806 CandidateSet.push_back(OverloadCandidate());
2807 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002808 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002809 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002810 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002811 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002812 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002813
2814 unsigned NumArgsInProto = Proto->getNumArgs();
2815
2816 // (C++ 13.3.2p2): A candidate function having fewer than m
2817 // parameters is viable only if it has an ellipsis in its parameter
2818 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002819 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2820 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002821 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002822 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002823 return;
2824 }
2825
2826 // (C++ 13.3.2p2): A candidate function having more than m parameters
2827 // is viable only if the (m+1)st parameter has a default argument
2828 // (8.3.6). For the purposes of overload resolution, the
2829 // parameter list is truncated on the right, so that there are
2830 // exactly m parameters.
2831 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002832 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002833 // Not enough arguments.
2834 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002835 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002836 return;
2837 }
2838
2839 // Determine the implicit conversion sequences for each of the
2840 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002841 Candidate.Conversions.resize(NumArgs);
2842 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2843 if (ArgIdx < NumArgsInProto) {
2844 // (C++ 13.3.2p3): for F to be a viable function, there shall
2845 // exist for each argument an implicit conversion sequence
2846 // (13.3.3.1) that converts that argument to the corresponding
2847 // parameter of F.
2848 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002849 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002850 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002851 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00002852 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002853 if (Candidate.Conversions[ArgIdx].isBad()) {
2854 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002855 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002856 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002857 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002858 } else {
2859 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2860 // argument for which there is no corresponding parameter is
2861 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002862 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002863 }
2864 }
2865}
2866
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002867/// \brief Add all of the function declarations in the given function set to
2868/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002869void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002870 Expr **Args, unsigned NumArgs,
2871 OverloadCandidateSet& CandidateSet,
2872 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002873 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00002874 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2875 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002876 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002877 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002878 cast<CXXMethodDecl>(FD)->getParent(),
2879 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002880 CandidateSet, SuppressUserConversions);
2881 else
John McCalla0296f72010-03-19 07:35:19 +00002882 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002883 SuppressUserConversions);
2884 } else {
John McCalla0296f72010-03-19 07:35:19 +00002885 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002886 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2887 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002888 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002889 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002890 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002891 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002892 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002893 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002894 else
John McCalla0296f72010-03-19 07:35:19 +00002895 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00002896 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002897 Args, NumArgs, CandidateSet,
2898 SuppressUserConversions);
2899 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002900 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002901}
2902
John McCallf0f1cf02009-11-17 07:50:12 +00002903/// AddMethodCandidate - Adds a named decl (which is some kind of
2904/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00002905void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002906 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002907 Expr **Args, unsigned NumArgs,
2908 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002909 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00002910 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002911 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002912
2913 if (isa<UsingShadowDecl>(Decl))
2914 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2915
2916 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2917 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2918 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00002919 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2920 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002921 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002922 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002923 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002924 } else {
John McCalla0296f72010-03-19 07:35:19 +00002925 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002926 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002927 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002928 }
2929}
2930
Douglas Gregor436424c2008-11-18 23:14:02 +00002931/// AddMethodCandidate - Adds the given C++ member function to the set
2932/// of candidate functions, using the given function call arguments
2933/// and the object argument (@c Object). For example, in a call
2934/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2935/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2936/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00002937/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00002938void
John McCalla0296f72010-03-19 07:35:19 +00002939Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002940 CXXRecordDecl *ActingContext, QualType ObjectType,
2941 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002942 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002943 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002944 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002945 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002946 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002947 assert(!isa<CXXConstructorDecl>(Method) &&
2948 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002949
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002950 if (!CandidateSet.isNewCandidate(Method))
2951 return;
2952
Douglas Gregor27381f32009-11-23 12:27:39 +00002953 // Overload resolution is always an unevaluated context.
2954 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2955
Douglas Gregor436424c2008-11-18 23:14:02 +00002956 // Add this candidate
2957 CandidateSet.push_back(OverloadCandidate());
2958 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002959 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00002960 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002961 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002962 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002963
2964 unsigned NumArgsInProto = Proto->getNumArgs();
2965
2966 // (C++ 13.3.2p2): A candidate function having fewer than m
2967 // parameters is viable only if it has an ellipsis in its parameter
2968 // list (8.3.5).
2969 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2970 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002971 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002972 return;
2973 }
2974
2975 // (C++ 13.3.2p2): A candidate function having more than m parameters
2976 // is viable only if the (m+1)st parameter has a default argument
2977 // (8.3.6). For the purposes of overload resolution, the
2978 // parameter list is truncated on the right, so that there are
2979 // exactly m parameters.
2980 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2981 if (NumArgs < MinRequiredArgs) {
2982 // Not enough arguments.
2983 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002984 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002985 return;
2986 }
2987
2988 Candidate.Viable = true;
2989 Candidate.Conversions.resize(NumArgs + 1);
2990
John McCall6e9f8f62009-12-03 04:06:58 +00002991 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002992 // The implicit object argument is ignored.
2993 Candidate.IgnoreObjectArgument = true;
2994 else {
2995 // Determine the implicit conversion sequence for the object
2996 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002997 Candidate.Conversions[0]
2998 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002999 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003000 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003001 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003002 return;
3003 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003004 }
3005
3006 // Determine the implicit conversion sequences for each of the
3007 // arguments.
3008 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3009 if (ArgIdx < NumArgsInProto) {
3010 // (C++ 13.3.2p3): for F to be a viable function, there shall
3011 // exist for each argument an implicit conversion sequence
3012 // (13.3.3.1) that converts that argument to the corresponding
3013 // parameter of F.
3014 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003015 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003016 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003017 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003018 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003019 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003020 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003021 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003022 break;
3023 }
3024 } else {
3025 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3026 // argument for which there is no corresponding parameter is
3027 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003028 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003029 }
3030 }
3031}
3032
Douglas Gregor97628d62009-08-21 00:16:32 +00003033/// \brief Add a C++ member function template as a candidate to the candidate
3034/// set, using template argument deduction to produce an appropriate member
3035/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003036void
Douglas Gregor97628d62009-08-21 00:16:32 +00003037Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003038 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003039 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003040 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003041 QualType ObjectType,
3042 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003043 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003044 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003045 if (!CandidateSet.isNewCandidate(MethodTmpl))
3046 return;
3047
Douglas Gregor97628d62009-08-21 00:16:32 +00003048 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003049 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003050 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003051 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003052 // candidate functions in the usual way.113) A given name can refer to one
3053 // or more function templates and also to a set of overloaded non-template
3054 // functions. In such a case, the candidate functions generated from each
3055 // function template are combined with the set of non-template candidate
3056 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003057 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003058 FunctionDecl *Specialization = 0;
3059 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003060 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003061 Args, NumArgs, Specialization, Info)) {
3062 // FIXME: Record what happened with template argument deduction, so
3063 // that we can give the user a beautiful diagnostic.
3064 (void)Result;
3065 return;
3066 }
Mike Stump11289f42009-09-09 15:08:12 +00003067
Douglas Gregor97628d62009-08-21 00:16:32 +00003068 // Add the function template specialization produced by template argument
3069 // deduction as a candidate.
3070 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003071 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003072 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003073 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003074 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003075 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003076}
3077
Douglas Gregor05155d82009-08-21 23:19:43 +00003078/// \brief Add a C++ function template specialization as a candidate
3079/// in the candidate set, using template argument deduction to produce
3080/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003081void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003082Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003083 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003084 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003085 Expr **Args, unsigned NumArgs,
3086 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003087 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003088 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3089 return;
3090
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003091 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003092 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003093 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003094 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003095 // candidate functions in the usual way.113) A given name can refer to one
3096 // or more function templates and also to a set of overloaded non-template
3097 // functions. In such a case, the candidate functions generated from each
3098 // function template are combined with the set of non-template candidate
3099 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003100 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003101 FunctionDecl *Specialization = 0;
3102 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003103 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003104 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003105 CandidateSet.push_back(OverloadCandidate());
3106 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003107 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003108 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3109 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003110 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003111 Candidate.IsSurrogate = false;
3112 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00003113
3114 // TODO: record more information about failed template arguments
3115 Candidate.DeductionFailure.Result = Result;
3116 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003117 return;
3118 }
Mike Stump11289f42009-09-09 15:08:12 +00003119
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003120 // Add the function template specialization produced by template argument
3121 // deduction as a candidate.
3122 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003123 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003124 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003125}
Mike Stump11289f42009-09-09 15:08:12 +00003126
Douglas Gregora1f013e2008-11-07 22:36:19 +00003127/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003128/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003129/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003130/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003131/// (which may or may not be the same type as the type that the
3132/// conversion function produces).
3133void
3134Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003135 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003136 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003137 Expr *From, QualType ToType,
3138 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003139 assert(!Conversion->getDescribedFunctionTemplate() &&
3140 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003141 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003142 if (!CandidateSet.isNewCandidate(Conversion))
3143 return;
3144
Douglas Gregor27381f32009-11-23 12:27:39 +00003145 // Overload resolution is always an unevaluated context.
3146 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3147
Douglas Gregora1f013e2008-11-07 22:36:19 +00003148 // Add this candidate
3149 CandidateSet.push_back(OverloadCandidate());
3150 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003151 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003152 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003153 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003154 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003155 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003156 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003157 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003158
Douglas Gregor436424c2008-11-18 23:14:02 +00003159 // Determine the implicit conversion sequence for the implicit
3160 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003161 Candidate.Viable = true;
3162 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003163 Candidate.Conversions[0]
3164 = TryObjectArgumentInitialization(From->getType(), Conversion,
3165 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003166 // Conversion functions to a different type in the base class is visible in
3167 // the derived class. So, a derived to base conversion should not participate
3168 // in overload resolution.
3169 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3170 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003171 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003172 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003173 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003174 return;
3175 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003176
3177 // We won't go through a user-define type conversion function to convert a
3178 // derived to base as such conversions are given Conversion Rank. They only
3179 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3180 QualType FromCanon
3181 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3182 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3183 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3184 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003185 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003186 return;
3187 }
3188
Douglas Gregora1f013e2008-11-07 22:36:19 +00003189 // To determine what the conversion from the result of calling the
3190 // conversion function to the type we're eventually trying to
3191 // convert to (ToType), we need to synthesize a call to the
3192 // conversion function and attempt copy initialization from it. This
3193 // makes sure that we get the right semantics with respect to
3194 // lvalues/rvalues and the type. Fortunately, we can allocate this
3195 // call on the stack and we don't need its arguments to be
3196 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003197 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003198 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003199 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003200 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003201 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003202
3203 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003204 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3205 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003206 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003207 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003208 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003209 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003210 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003211 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003212 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003213
John McCall0d1da222010-01-12 00:44:57 +00003214 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003215 case ImplicitConversionSequence::StandardConversion:
3216 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003217
3218 // C++ [over.ics.user]p3:
3219 // If the user-defined conversion is specified by a specialization of a
3220 // conversion function template, the second standard conversion sequence
3221 // shall have exact match rank.
3222 if (Conversion->getPrimaryTemplate() &&
3223 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3224 Candidate.Viable = false;
3225 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3226 }
3227
Douglas Gregora1f013e2008-11-07 22:36:19 +00003228 break;
3229
3230 case ImplicitConversionSequence::BadConversion:
3231 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003232 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003233 break;
3234
3235 default:
Mike Stump11289f42009-09-09 15:08:12 +00003236 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003237 "Can only end up with a standard conversion sequence or failure");
3238 }
3239}
3240
Douglas Gregor05155d82009-08-21 23:19:43 +00003241/// \brief Adds a conversion function template specialization
3242/// candidate to the overload set, using template argument deduction
3243/// to deduce the template arguments of the conversion function
3244/// template from the type that we are converting to (C++
3245/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003246void
Douglas Gregor05155d82009-08-21 23:19:43 +00003247Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003248 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003249 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003250 Expr *From, QualType ToType,
3251 OverloadCandidateSet &CandidateSet) {
3252 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3253 "Only conversion function templates permitted here");
3254
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003255 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3256 return;
3257
John McCallbc077cf2010-02-08 23:07:23 +00003258 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003259 CXXConversionDecl *Specialization = 0;
3260 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003261 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003262 Specialization, Info)) {
3263 // FIXME: Record what happened with template argument deduction, so
3264 // that we can give the user a beautiful diagnostic.
3265 (void)Result;
3266 return;
3267 }
Mike Stump11289f42009-09-09 15:08:12 +00003268
Douglas Gregor05155d82009-08-21 23:19:43 +00003269 // Add the conversion function template specialization produced by
3270 // template argument deduction as a candidate.
3271 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003272 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003273 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003274}
3275
Douglas Gregorab7897a2008-11-19 22:57:39 +00003276/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3277/// converts the given @c Object to a function pointer via the
3278/// conversion function @c Conversion, and then attempts to call it
3279/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3280/// the type of function that we'll eventually be calling.
3281void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003282 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003283 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003284 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003285 QualType ObjectType,
3286 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003287 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003288 if (!CandidateSet.isNewCandidate(Conversion))
3289 return;
3290
Douglas Gregor27381f32009-11-23 12:27:39 +00003291 // Overload resolution is always an unevaluated context.
3292 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3293
Douglas Gregorab7897a2008-11-19 22:57:39 +00003294 CandidateSet.push_back(OverloadCandidate());
3295 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003296 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003297 Candidate.Function = 0;
3298 Candidate.Surrogate = Conversion;
3299 Candidate.Viable = true;
3300 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003301 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003302 Candidate.Conversions.resize(NumArgs + 1);
3303
3304 // Determine the implicit conversion sequence for the implicit
3305 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003306 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003307 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003308 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003309 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003310 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003311 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003312 return;
3313 }
3314
3315 // The first conversion is actually a user-defined conversion whose
3316 // first conversion is ObjectInit's standard conversion (which is
3317 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003318 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003319 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003320 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003321 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003322 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003323 = Candidate.Conversions[0].UserDefined.Before;
3324 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3325
Mike Stump11289f42009-09-09 15:08:12 +00003326 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003327 unsigned NumArgsInProto = Proto->getNumArgs();
3328
3329 // (C++ 13.3.2p2): A candidate function having fewer than m
3330 // parameters is viable only if it has an ellipsis in its parameter
3331 // list (8.3.5).
3332 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3333 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003334 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003335 return;
3336 }
3337
3338 // Function types don't have any default arguments, so just check if
3339 // we have enough arguments.
3340 if (NumArgs < NumArgsInProto) {
3341 // Not enough arguments.
3342 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003343 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003344 return;
3345 }
3346
3347 // Determine the implicit conversion sequences for each of the
3348 // arguments.
3349 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3350 if (ArgIdx < NumArgsInProto) {
3351 // (C++ 13.3.2p3): for F to be a viable function, there shall
3352 // exist for each argument an implicit conversion sequence
3353 // (13.3.3.1) that converts that argument to the corresponding
3354 // parameter of F.
3355 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003356 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003357 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003358 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003359 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003360 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003361 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003362 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003363 break;
3364 }
3365 } else {
3366 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3367 // argument for which there is no corresponding parameter is
3368 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003369 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003370 }
3371 }
3372}
3373
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003374/// \brief Add overload candidates for overloaded operators that are
3375/// member functions.
3376///
3377/// Add the overloaded operator candidates that are member functions
3378/// for the operator Op that was used in an operator expression such
3379/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3380/// CandidateSet will store the added overload candidates. (C++
3381/// [over.match.oper]).
3382void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3383 SourceLocation OpLoc,
3384 Expr **Args, unsigned NumArgs,
3385 OverloadCandidateSet& CandidateSet,
3386 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003387 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3388
3389 // C++ [over.match.oper]p3:
3390 // For a unary operator @ with an operand of a type whose
3391 // cv-unqualified version is T1, and for a binary operator @ with
3392 // a left operand of a type whose cv-unqualified version is T1 and
3393 // a right operand of a type whose cv-unqualified version is T2,
3394 // three sets of candidate functions, designated member
3395 // candidates, non-member candidates and built-in candidates, are
3396 // constructed as follows:
3397 QualType T1 = Args[0]->getType();
3398 QualType T2;
3399 if (NumArgs > 1)
3400 T2 = Args[1]->getType();
3401
3402 // -- If T1 is a class type, the set of member candidates is the
3403 // result of the qualified lookup of T1::operator@
3404 // (13.3.1.1.1); otherwise, the set of member candidates is
3405 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003406 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003407 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003408 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003409 return;
Mike Stump11289f42009-09-09 15:08:12 +00003410
John McCall27b18f82009-11-17 02:14:36 +00003411 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3412 LookupQualifiedName(Operators, T1Rec->getDecl());
3413 Operators.suppressDiagnostics();
3414
Mike Stump11289f42009-09-09 15:08:12 +00003415 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003416 OperEnd = Operators.end();
3417 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003418 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003419 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003420 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003421 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003422 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003423}
3424
Douglas Gregora11693b2008-11-12 17:17:38 +00003425/// AddBuiltinCandidate - Add a candidate for a built-in
3426/// operator. ResultTy and ParamTys are the result and parameter types
3427/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003428/// arguments being passed to the candidate. IsAssignmentOperator
3429/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003430/// operator. NumContextualBoolArguments is the number of arguments
3431/// (at the beginning of the argument list) that will be contextually
3432/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003433void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003434 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003435 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003436 bool IsAssignmentOperator,
3437 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003438 // Overload resolution is always an unevaluated context.
3439 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3440
Douglas Gregora11693b2008-11-12 17:17:38 +00003441 // Add this candidate
3442 CandidateSet.push_back(OverloadCandidate());
3443 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003444 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003445 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003446 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003447 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003448 Candidate.BuiltinTypes.ResultTy = ResultTy;
3449 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3450 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3451
3452 // Determine the implicit conversion sequences for each of the
3453 // arguments.
3454 Candidate.Viable = true;
3455 Candidate.Conversions.resize(NumArgs);
3456 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003457 // C++ [over.match.oper]p4:
3458 // For the built-in assignment operators, conversions of the
3459 // left operand are restricted as follows:
3460 // -- no temporaries are introduced to hold the left operand, and
3461 // -- no user-defined conversions are applied to the left
3462 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003463 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003464 //
3465 // We block these conversions by turning off user-defined
3466 // conversions, since that is the only way that initialization of
3467 // a reference to a non-class type can occur from something that
3468 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003469 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003470 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003471 "Contextual conversion to bool requires bool type");
3472 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3473 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003474 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003475 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003476 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003477 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003478 }
John McCall0d1da222010-01-12 00:44:57 +00003479 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003480 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003481 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003482 break;
3483 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003484 }
3485}
3486
3487/// BuiltinCandidateTypeSet - A set of types that will be used for the
3488/// candidate operator functions for built-in operators (C++
3489/// [over.built]). The types are separated into pointer types and
3490/// enumeration types.
3491class BuiltinCandidateTypeSet {
3492 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003493 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003494
3495 /// PointerTypes - The set of pointer types that will be used in the
3496 /// built-in candidates.
3497 TypeSet PointerTypes;
3498
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003499 /// MemberPointerTypes - The set of member pointer types that will be
3500 /// used in the built-in candidates.
3501 TypeSet MemberPointerTypes;
3502
Douglas Gregora11693b2008-11-12 17:17:38 +00003503 /// EnumerationTypes - The set of enumeration types that will be
3504 /// used in the built-in candidates.
3505 TypeSet EnumerationTypes;
3506
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003507 /// Sema - The semantic analysis instance where we are building the
3508 /// candidate type set.
3509 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003510
Douglas Gregora11693b2008-11-12 17:17:38 +00003511 /// Context - The AST context in which we will build the type sets.
3512 ASTContext &Context;
3513
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003514 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3515 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003516 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003517
3518public:
3519 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003520 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003521
Mike Stump11289f42009-09-09 15:08:12 +00003522 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003523 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003524
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003525 void AddTypesConvertedFrom(QualType Ty,
3526 SourceLocation Loc,
3527 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003528 bool AllowExplicitConversions,
3529 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003530
3531 /// pointer_begin - First pointer type found;
3532 iterator pointer_begin() { return PointerTypes.begin(); }
3533
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003534 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003535 iterator pointer_end() { return PointerTypes.end(); }
3536
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003537 /// member_pointer_begin - First member pointer type found;
3538 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3539
3540 /// member_pointer_end - Past the last member pointer type found;
3541 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3542
Douglas Gregora11693b2008-11-12 17:17:38 +00003543 /// enumeration_begin - First enumeration type found;
3544 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3545
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003546 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003547 iterator enumeration_end() { return EnumerationTypes.end(); }
3548};
3549
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003550/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003551/// the set of pointer types along with any more-qualified variants of
3552/// that type. For example, if @p Ty is "int const *", this routine
3553/// will add "int const *", "int const volatile *", "int const
3554/// restrict *", and "int const volatile restrict *" to the set of
3555/// pointer types. Returns true if the add of @p Ty itself succeeded,
3556/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003557///
3558/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003559bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003560BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3561 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003562
Douglas Gregora11693b2008-11-12 17:17:38 +00003563 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003564 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003565 return false;
3566
John McCall8ccfcb52009-09-24 19:53:00 +00003567 const PointerType *PointerTy = Ty->getAs<PointerType>();
3568 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003569
John McCall8ccfcb52009-09-24 19:53:00 +00003570 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003571 // Don't add qualified variants of arrays. For one, they're not allowed
3572 // (the qualifier would sink to the element type), and for another, the
3573 // only overload situation where it matters is subscript or pointer +- int,
3574 // and those shouldn't have qualifier variants anyway.
3575 if (PointeeTy->isArrayType())
3576 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003577 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003578 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003579 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003580 bool hasVolatile = VisibleQuals.hasVolatile();
3581 bool hasRestrict = VisibleQuals.hasRestrict();
3582
John McCall8ccfcb52009-09-24 19:53:00 +00003583 // Iterate through all strict supersets of BaseCVR.
3584 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3585 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003586 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3587 // in the types.
3588 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3589 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003590 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3591 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003592 }
3593
3594 return true;
3595}
3596
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003597/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3598/// to the set of pointer types along with any more-qualified variants of
3599/// that type. For example, if @p Ty is "int const *", this routine
3600/// will add "int const *", "int const volatile *", "int const
3601/// restrict *", and "int const volatile restrict *" to the set of
3602/// pointer types. Returns true if the add of @p Ty itself succeeded,
3603/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003604///
3605/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003606bool
3607BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3608 QualType Ty) {
3609 // Insert this type.
3610 if (!MemberPointerTypes.insert(Ty))
3611 return false;
3612
John McCall8ccfcb52009-09-24 19:53:00 +00003613 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3614 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003615
John McCall8ccfcb52009-09-24 19:53:00 +00003616 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003617 // Don't add qualified variants of arrays. For one, they're not allowed
3618 // (the qualifier would sink to the element type), and for another, the
3619 // only overload situation where it matters is subscript or pointer +- int,
3620 // and those shouldn't have qualifier variants anyway.
3621 if (PointeeTy->isArrayType())
3622 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003623 const Type *ClassTy = PointerTy->getClass();
3624
3625 // Iterate through all strict supersets of the pointee type's CVR
3626 // qualifiers.
3627 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3628 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3629 if ((CVR | BaseCVR) != CVR) continue;
3630
3631 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3632 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003633 }
3634
3635 return true;
3636}
3637
Douglas Gregora11693b2008-11-12 17:17:38 +00003638/// AddTypesConvertedFrom - Add each of the types to which the type @p
3639/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003640/// primarily interested in pointer types and enumeration types. We also
3641/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003642/// AllowUserConversions is true if we should look at the conversion
3643/// functions of a class type, and AllowExplicitConversions if we
3644/// should also include the explicit conversion functions of a class
3645/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003646void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003647BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003648 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003649 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003650 bool AllowExplicitConversions,
3651 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003652 // Only deal with canonical types.
3653 Ty = Context.getCanonicalType(Ty);
3654
3655 // Look through reference types; they aren't part of the type of an
3656 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003657 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003658 Ty = RefTy->getPointeeType();
3659
3660 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003661 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003662
Sebastian Redl65ae2002009-11-05 16:36:20 +00003663 // If we're dealing with an array type, decay to the pointer.
3664 if (Ty->isArrayType())
3665 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3666
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003667 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003668 QualType PointeeTy = PointerTy->getPointeeType();
3669
3670 // Insert our type, and its more-qualified variants, into the set
3671 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003672 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003673 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003674 } else if (Ty->isMemberPointerType()) {
3675 // Member pointers are far easier, since the pointee can't be converted.
3676 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3677 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003678 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003679 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003680 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003681 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003682 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003683 // No conversion functions in incomplete types.
3684 return;
3685 }
Mike Stump11289f42009-09-09 15:08:12 +00003686
Douglas Gregora11693b2008-11-12 17:17:38 +00003687 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003688 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003689 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003690 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003691 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003692 NamedDecl *D = I.getDecl();
3693 if (isa<UsingShadowDecl>(D))
3694 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003695
Mike Stump11289f42009-09-09 15:08:12 +00003696 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003697 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003698 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003699 continue;
3700
John McCallda4458e2010-03-31 01:36:47 +00003701 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003702 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003703 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003704 VisibleQuals);
3705 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003706 }
3707 }
3708 }
3709}
3710
Douglas Gregor84605ae2009-08-24 13:43:27 +00003711/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3712/// the volatile- and non-volatile-qualified assignment operators for the
3713/// given type to the candidate set.
3714static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3715 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003716 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003717 unsigned NumArgs,
3718 OverloadCandidateSet &CandidateSet) {
3719 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003720
Douglas Gregor84605ae2009-08-24 13:43:27 +00003721 // T& operator=(T&, T)
3722 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3723 ParamTypes[1] = T;
3724 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3725 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003726
Douglas Gregor84605ae2009-08-24 13:43:27 +00003727 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3728 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003729 ParamTypes[0]
3730 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003731 ParamTypes[1] = T;
3732 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003733 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003734 }
3735}
Mike Stump11289f42009-09-09 15:08:12 +00003736
Sebastian Redl1054fae2009-10-25 17:03:50 +00003737/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3738/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003739static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3740 Qualifiers VRQuals;
3741 const RecordType *TyRec;
3742 if (const MemberPointerType *RHSMPType =
3743 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00003744 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003745 else
3746 TyRec = ArgExpr->getType()->getAs<RecordType>();
3747 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003748 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003749 VRQuals.addVolatile();
3750 VRQuals.addRestrict();
3751 return VRQuals;
3752 }
3753
3754 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003755 if (!ClassDecl->hasDefinition())
3756 return VRQuals;
3757
John McCallad371252010-01-20 00:46:10 +00003758 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003759 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003760
John McCallad371252010-01-20 00:46:10 +00003761 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003762 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003763 NamedDecl *D = I.getDecl();
3764 if (isa<UsingShadowDecl>(D))
3765 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3766 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003767 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3768 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3769 CanTy = ResTypeRef->getPointeeType();
3770 // Need to go down the pointer/mempointer chain and add qualifiers
3771 // as see them.
3772 bool done = false;
3773 while (!done) {
3774 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3775 CanTy = ResTypePtr->getPointeeType();
3776 else if (const MemberPointerType *ResTypeMPtr =
3777 CanTy->getAs<MemberPointerType>())
3778 CanTy = ResTypeMPtr->getPointeeType();
3779 else
3780 done = true;
3781 if (CanTy.isVolatileQualified())
3782 VRQuals.addVolatile();
3783 if (CanTy.isRestrictQualified())
3784 VRQuals.addRestrict();
3785 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3786 return VRQuals;
3787 }
3788 }
3789 }
3790 return VRQuals;
3791}
3792
Douglas Gregord08452f2008-11-19 15:42:04 +00003793/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3794/// operator overloads to the candidate set (C++ [over.built]), based
3795/// on the operator @p Op and the arguments given. For example, if the
3796/// operator is a binary '+', this routine might add "int
3797/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003798void
Mike Stump11289f42009-09-09 15:08:12 +00003799Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003800 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003801 Expr **Args, unsigned NumArgs,
3802 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003803 // The set of "promoted arithmetic types", which are the arithmetic
3804 // types are that preserved by promotion (C++ [over.built]p2). Note
3805 // that the first few of these types are the promoted integral
3806 // types; these types need to be first.
3807 // FIXME: What about complex?
3808 const unsigned FirstIntegralType = 0;
3809 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003810 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003811 LastPromotedIntegralType = 13;
3812 const unsigned FirstPromotedArithmeticType = 7,
3813 LastPromotedArithmeticType = 16;
3814 const unsigned NumArithmeticTypes = 16;
3815 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003816 Context.BoolTy, Context.CharTy, Context.WCharTy,
3817// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003818 Context.SignedCharTy, Context.ShortTy,
3819 Context.UnsignedCharTy, Context.UnsignedShortTy,
3820 Context.IntTy, Context.LongTy, Context.LongLongTy,
3821 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3822 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3823 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003824 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3825 "Invalid first promoted integral type");
3826 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3827 == Context.UnsignedLongLongTy &&
3828 "Invalid last promoted integral type");
3829 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3830 "Invalid first promoted arithmetic type");
3831 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3832 == Context.LongDoubleTy &&
3833 "Invalid last promoted arithmetic type");
3834
Douglas Gregora11693b2008-11-12 17:17:38 +00003835 // Find all of the types that the arguments can convert to, but only
3836 // if the operator we're looking at has built-in operator candidates
3837 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003838 Qualifiers VisibleTypeConversionsQuals;
3839 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003840 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3841 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3842
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003843 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003844 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3845 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003846 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003847 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003848 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003849 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003850 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003851 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003852 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003853 true,
3854 (Op == OO_Exclaim ||
3855 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003856 Op == OO_PipePipe),
3857 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003858 }
3859
3860 bool isComparison = false;
3861 switch (Op) {
3862 case OO_None:
3863 case NUM_OVERLOADED_OPERATORS:
3864 assert(false && "Expected an overloaded operator");
3865 break;
3866
Douglas Gregord08452f2008-11-19 15:42:04 +00003867 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003868 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003869 goto UnaryStar;
3870 else
3871 goto BinaryStar;
3872 break;
3873
3874 case OO_Plus: // '+' is either unary or binary
3875 if (NumArgs == 1)
3876 goto UnaryPlus;
3877 else
3878 goto BinaryPlus;
3879 break;
3880
3881 case OO_Minus: // '-' is either unary or binary
3882 if (NumArgs == 1)
3883 goto UnaryMinus;
3884 else
3885 goto BinaryMinus;
3886 break;
3887
3888 case OO_Amp: // '&' is either unary or binary
3889 if (NumArgs == 1)
3890 goto UnaryAmp;
3891 else
3892 goto BinaryAmp;
3893
3894 case OO_PlusPlus:
3895 case OO_MinusMinus:
3896 // C++ [over.built]p3:
3897 //
3898 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3899 // is either volatile or empty, there exist candidate operator
3900 // functions of the form
3901 //
3902 // VQ T& operator++(VQ T&);
3903 // T operator++(VQ T&, int);
3904 //
3905 // C++ [over.built]p4:
3906 //
3907 // For every pair (T, VQ), where T is an arithmetic type other
3908 // than bool, and VQ is either volatile or empty, there exist
3909 // candidate operator functions of the form
3910 //
3911 // VQ T& operator--(VQ T&);
3912 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003913 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003914 Arith < NumArithmeticTypes; ++Arith) {
3915 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003916 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003917 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003918
3919 // Non-volatile version.
3920 if (NumArgs == 1)
3921 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3922 else
3923 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003924 // heuristic to reduce number of builtin candidates in the set.
3925 // Add volatile version only if there are conversions to a volatile type.
3926 if (VisibleTypeConversionsQuals.hasVolatile()) {
3927 // Volatile version
3928 ParamTypes[0]
3929 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3930 if (NumArgs == 1)
3931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3932 else
3933 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3934 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003935 }
3936
3937 // C++ [over.built]p5:
3938 //
3939 // For every pair (T, VQ), where T is a cv-qualified or
3940 // cv-unqualified object type, and VQ is either volatile or
3941 // empty, there exist candidate operator functions of the form
3942 //
3943 // T*VQ& operator++(T*VQ&);
3944 // T*VQ& operator--(T*VQ&);
3945 // T* operator++(T*VQ&, int);
3946 // T* operator--(T*VQ&, int);
3947 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3948 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3949 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003950 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003951 continue;
3952
Mike Stump11289f42009-09-09 15:08:12 +00003953 QualType ParamTypes[2] = {
3954 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003955 };
Mike Stump11289f42009-09-09 15:08:12 +00003956
Douglas Gregord08452f2008-11-19 15:42:04 +00003957 // Without volatile
3958 if (NumArgs == 1)
3959 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3960 else
3961 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3962
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003963 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3964 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003965 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003966 ParamTypes[0]
3967 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003968 if (NumArgs == 1)
3969 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3970 else
3971 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3972 }
3973 }
3974 break;
3975
3976 UnaryStar:
3977 // C++ [over.built]p6:
3978 // For every cv-qualified or cv-unqualified object type T, there
3979 // exist candidate operator functions of the form
3980 //
3981 // T& operator*(T*);
3982 //
3983 // C++ [over.built]p7:
3984 // For every function type T, there exist candidate operator
3985 // functions of the form
3986 // T& operator*(T*);
3987 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3988 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3989 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003990 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003991 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003992 &ParamTy, Args, 1, CandidateSet);
3993 }
3994 break;
3995
3996 UnaryPlus:
3997 // C++ [over.built]p8:
3998 // For every type T, there exist candidate operator functions of
3999 // the form
4000 //
4001 // T* operator+(T*);
4002 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4003 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4004 QualType ParamTy = *Ptr;
4005 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4006 }
Mike Stump11289f42009-09-09 15:08:12 +00004007
Douglas Gregord08452f2008-11-19 15:42:04 +00004008 // Fall through
4009
4010 UnaryMinus:
4011 // C++ [over.built]p9:
4012 // For every promoted arithmetic type T, there exist candidate
4013 // operator functions of the form
4014 //
4015 // T operator+(T);
4016 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004017 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004018 Arith < LastPromotedArithmeticType; ++Arith) {
4019 QualType ArithTy = ArithmeticTypes[Arith];
4020 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4021 }
4022 break;
4023
4024 case OO_Tilde:
4025 // C++ [over.built]p10:
4026 // For every promoted integral type T, there exist candidate
4027 // operator functions of the form
4028 //
4029 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004030 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004031 Int < LastPromotedIntegralType; ++Int) {
4032 QualType IntTy = ArithmeticTypes[Int];
4033 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4034 }
4035 break;
4036
Douglas Gregora11693b2008-11-12 17:17:38 +00004037 case OO_New:
4038 case OO_Delete:
4039 case OO_Array_New:
4040 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004041 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004042 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004043 break;
4044
4045 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004046 UnaryAmp:
4047 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004048 // C++ [over.match.oper]p3:
4049 // -- For the operator ',', the unary operator '&', or the
4050 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004051 break;
4052
Douglas Gregor84605ae2009-08-24 13:43:27 +00004053 case OO_EqualEqual:
4054 case OO_ExclaimEqual:
4055 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004056 // For every pointer to member type T, there exist candidate operator
4057 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004058 //
4059 // bool operator==(T,T);
4060 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004061 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004062 MemPtr = CandidateTypes.member_pointer_begin(),
4063 MemPtrEnd = CandidateTypes.member_pointer_end();
4064 MemPtr != MemPtrEnd;
4065 ++MemPtr) {
4066 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4067 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4068 }
Mike Stump11289f42009-09-09 15:08:12 +00004069
Douglas Gregor84605ae2009-08-24 13:43:27 +00004070 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004071
Douglas Gregora11693b2008-11-12 17:17:38 +00004072 case OO_Less:
4073 case OO_Greater:
4074 case OO_LessEqual:
4075 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004076 // C++ [over.built]p15:
4077 //
4078 // For every pointer or enumeration type T, there exist
4079 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004080 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004081 // bool operator<(T, T);
4082 // bool operator>(T, T);
4083 // bool operator<=(T, T);
4084 // bool operator>=(T, T);
4085 // bool operator==(T, T);
4086 // bool operator!=(T, T);
4087 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4088 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4089 QualType ParamTypes[2] = { *Ptr, *Ptr };
4090 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4091 }
Mike Stump11289f42009-09-09 15:08:12 +00004092 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004093 = CandidateTypes.enumeration_begin();
4094 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4095 QualType ParamTypes[2] = { *Enum, *Enum };
4096 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4097 }
4098
4099 // Fall through.
4100 isComparison = true;
4101
Douglas Gregord08452f2008-11-19 15:42:04 +00004102 BinaryPlus:
4103 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004104 if (!isComparison) {
4105 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4106
4107 // C++ [over.built]p13:
4108 //
4109 // For every cv-qualified or cv-unqualified object type T
4110 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004111 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004112 // T* operator+(T*, ptrdiff_t);
4113 // T& operator[](T*, ptrdiff_t); [BELOW]
4114 // T* operator-(T*, ptrdiff_t);
4115 // T* operator+(ptrdiff_t, T*);
4116 // T& operator[](ptrdiff_t, T*); [BELOW]
4117 //
4118 // C++ [over.built]p14:
4119 //
4120 // For every T, where T is a pointer to object type, there
4121 // exist candidate operator functions of the form
4122 //
4123 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004124 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004125 = CandidateTypes.pointer_begin();
4126 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4127 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4128
4129 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4130 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4131
4132 if (Op == OO_Plus) {
4133 // T* operator+(ptrdiff_t, T*);
4134 ParamTypes[0] = ParamTypes[1];
4135 ParamTypes[1] = *Ptr;
4136 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4137 } else {
4138 // ptrdiff_t operator-(T, T);
4139 ParamTypes[1] = *Ptr;
4140 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4141 Args, 2, CandidateSet);
4142 }
4143 }
4144 }
4145 // Fall through
4146
Douglas Gregora11693b2008-11-12 17:17:38 +00004147 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004148 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004149 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004150 // C++ [over.built]p12:
4151 //
4152 // For every pair of promoted arithmetic types L and R, there
4153 // exist candidate operator functions of the form
4154 //
4155 // LR operator*(L, R);
4156 // LR operator/(L, R);
4157 // LR operator+(L, R);
4158 // LR operator-(L, R);
4159 // bool operator<(L, R);
4160 // bool operator>(L, R);
4161 // bool operator<=(L, R);
4162 // bool operator>=(L, R);
4163 // bool operator==(L, R);
4164 // bool operator!=(L, R);
4165 //
4166 // where LR is the result of the usual arithmetic conversions
4167 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004168 //
4169 // C++ [over.built]p24:
4170 //
4171 // For every pair of promoted arithmetic types L and R, there exist
4172 // candidate operator functions of the form
4173 //
4174 // LR operator?(bool, L, R);
4175 //
4176 // where LR is the result of the usual arithmetic conversions
4177 // between types L and R.
4178 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004179 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004180 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004181 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004182 Right < LastPromotedArithmeticType; ++Right) {
4183 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004184 QualType Result
4185 = isComparison
4186 ? Context.BoolTy
4187 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004188 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4189 }
4190 }
4191 break;
4192
4193 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004194 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004195 case OO_Caret:
4196 case OO_Pipe:
4197 case OO_LessLess:
4198 case OO_GreaterGreater:
4199 // C++ [over.built]p17:
4200 //
4201 // For every pair of promoted integral types L and R, there
4202 // exist candidate operator functions of the form
4203 //
4204 // LR operator%(L, R);
4205 // LR operator&(L, R);
4206 // LR operator^(L, R);
4207 // LR operator|(L, R);
4208 // L operator<<(L, R);
4209 // L operator>>(L, R);
4210 //
4211 // where LR is the result of the usual arithmetic conversions
4212 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004213 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004214 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004215 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004216 Right < LastPromotedIntegralType; ++Right) {
4217 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4218 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4219 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004220 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004221 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4222 }
4223 }
4224 break;
4225
4226 case OO_Equal:
4227 // C++ [over.built]p20:
4228 //
4229 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004230 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004231 // empty, there exist candidate operator functions of the form
4232 //
4233 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004234 for (BuiltinCandidateTypeSet::iterator
4235 Enum = CandidateTypes.enumeration_begin(),
4236 EnumEnd = CandidateTypes.enumeration_end();
4237 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004238 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004239 CandidateSet);
4240 for (BuiltinCandidateTypeSet::iterator
4241 MemPtr = CandidateTypes.member_pointer_begin(),
4242 MemPtrEnd = CandidateTypes.member_pointer_end();
4243 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004244 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004245 CandidateSet);
4246 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004247
4248 case OO_PlusEqual:
4249 case OO_MinusEqual:
4250 // C++ [over.built]p19:
4251 //
4252 // For every pair (T, VQ), where T is any type and VQ is either
4253 // volatile or empty, there exist candidate operator functions
4254 // of the form
4255 //
4256 // T*VQ& operator=(T*VQ&, T*);
4257 //
4258 // C++ [over.built]p21:
4259 //
4260 // For every pair (T, VQ), where T is a cv-qualified or
4261 // cv-unqualified object type and VQ is either volatile or
4262 // empty, there exist candidate operator functions of the form
4263 //
4264 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4265 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4266 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4267 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4268 QualType ParamTypes[2];
4269 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4270
4271 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004272 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004273 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4274 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004275
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004276 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4277 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004278 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004279 ParamTypes[0]
4280 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004281 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4282 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004283 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004284 }
4285 // Fall through.
4286
4287 case OO_StarEqual:
4288 case OO_SlashEqual:
4289 // C++ [over.built]p18:
4290 //
4291 // For every triple (L, VQ, R), where L is an arithmetic type,
4292 // VQ is either volatile or empty, and R is a promoted
4293 // arithmetic type, there exist candidate operator functions of
4294 // the form
4295 //
4296 // VQ L& operator=(VQ L&, R);
4297 // VQ L& operator*=(VQ L&, R);
4298 // VQ L& operator/=(VQ L&, R);
4299 // VQ L& operator+=(VQ L&, R);
4300 // VQ L& operator-=(VQ L&, R);
4301 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004302 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004303 Right < LastPromotedArithmeticType; ++Right) {
4304 QualType ParamTypes[2];
4305 ParamTypes[1] = ArithmeticTypes[Right];
4306
4307 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004308 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004309 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4310 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004311
4312 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004313 if (VisibleTypeConversionsQuals.hasVolatile()) {
4314 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4315 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4316 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4317 /*IsAssigmentOperator=*/Op == OO_Equal);
4318 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004319 }
4320 }
4321 break;
4322
4323 case OO_PercentEqual:
4324 case OO_LessLessEqual:
4325 case OO_GreaterGreaterEqual:
4326 case OO_AmpEqual:
4327 case OO_CaretEqual:
4328 case OO_PipeEqual:
4329 // C++ [over.built]p22:
4330 //
4331 // For every triple (L, VQ, R), where L is an integral type, VQ
4332 // is either volatile or empty, and R is a promoted integral
4333 // type, there exist candidate operator functions of the form
4334 //
4335 // VQ L& operator%=(VQ L&, R);
4336 // VQ L& operator<<=(VQ L&, R);
4337 // VQ L& operator>>=(VQ L&, R);
4338 // VQ L& operator&=(VQ L&, R);
4339 // VQ L& operator^=(VQ L&, R);
4340 // VQ L& operator|=(VQ L&, R);
4341 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004342 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004343 Right < LastPromotedIntegralType; ++Right) {
4344 QualType ParamTypes[2];
4345 ParamTypes[1] = ArithmeticTypes[Right];
4346
4347 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004348 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004349 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004350 if (VisibleTypeConversionsQuals.hasVolatile()) {
4351 // Add this built-in operator as a candidate (VQ is 'volatile').
4352 ParamTypes[0] = ArithmeticTypes[Left];
4353 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4354 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4355 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4356 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004357 }
4358 }
4359 break;
4360
Douglas Gregord08452f2008-11-19 15:42:04 +00004361 case OO_Exclaim: {
4362 // C++ [over.operator]p23:
4363 //
4364 // There also exist candidate operator functions of the form
4365 //
Mike Stump11289f42009-09-09 15:08:12 +00004366 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004367 // bool operator&&(bool, bool); [BELOW]
4368 // bool operator||(bool, bool); [BELOW]
4369 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004370 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4371 /*IsAssignmentOperator=*/false,
4372 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004373 break;
4374 }
4375
Douglas Gregora11693b2008-11-12 17:17:38 +00004376 case OO_AmpAmp:
4377 case OO_PipePipe: {
4378 // C++ [over.operator]p23:
4379 //
4380 // There also exist candidate operator functions of the form
4381 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004382 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004383 // bool operator&&(bool, bool);
4384 // bool operator||(bool, bool);
4385 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004386 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4387 /*IsAssignmentOperator=*/false,
4388 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004389 break;
4390 }
4391
4392 case OO_Subscript:
4393 // C++ [over.built]p13:
4394 //
4395 // For every cv-qualified or cv-unqualified object type T there
4396 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004397 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004398 // T* operator+(T*, ptrdiff_t); [ABOVE]
4399 // T& operator[](T*, ptrdiff_t);
4400 // T* operator-(T*, ptrdiff_t); [ABOVE]
4401 // T* operator+(ptrdiff_t, T*); [ABOVE]
4402 // T& operator[](ptrdiff_t, T*);
4403 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4404 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4405 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004406 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004407 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004408
4409 // T& operator[](T*, ptrdiff_t)
4410 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4411
4412 // T& operator[](ptrdiff_t, T*);
4413 ParamTypes[0] = ParamTypes[1];
4414 ParamTypes[1] = *Ptr;
4415 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4416 }
4417 break;
4418
4419 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004420 // C++ [over.built]p11:
4421 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4422 // C1 is the same type as C2 or is a derived class of C2, T is an object
4423 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4424 // there exist candidate operator functions of the form
4425 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4426 // where CV12 is the union of CV1 and CV2.
4427 {
4428 for (BuiltinCandidateTypeSet::iterator Ptr =
4429 CandidateTypes.pointer_begin();
4430 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4431 QualType C1Ty = (*Ptr);
4432 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004433 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004434 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004435 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004436 if (!isa<RecordType>(C1))
4437 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004438 // heuristic to reduce number of builtin candidates in the set.
4439 // Add volatile/restrict version only if there are conversions to a
4440 // volatile/restrict type.
4441 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4442 continue;
4443 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4444 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004445 }
4446 for (BuiltinCandidateTypeSet::iterator
4447 MemPtr = CandidateTypes.member_pointer_begin(),
4448 MemPtrEnd = CandidateTypes.member_pointer_end();
4449 MemPtr != MemPtrEnd; ++MemPtr) {
4450 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4451 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004452 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004453 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4454 break;
4455 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4456 // build CV12 T&
4457 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004458 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4459 T.isVolatileQualified())
4460 continue;
4461 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4462 T.isRestrictQualified())
4463 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004464 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004465 QualType ResultTy = Context.getLValueReferenceType(T);
4466 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4467 }
4468 }
4469 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004470 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004471
4472 case OO_Conditional:
4473 // Note that we don't consider the first argument, since it has been
4474 // contextually converted to bool long ago. The candidates below are
4475 // therefore added as binary.
4476 //
4477 // C++ [over.built]p24:
4478 // For every type T, where T is a pointer or pointer-to-member type,
4479 // there exist candidate operator functions of the form
4480 //
4481 // T operator?(bool, T, T);
4482 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004483 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4484 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4485 QualType ParamTypes[2] = { *Ptr, *Ptr };
4486 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4487 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004488 for (BuiltinCandidateTypeSet::iterator Ptr =
4489 CandidateTypes.member_pointer_begin(),
4490 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4491 QualType ParamTypes[2] = { *Ptr, *Ptr };
4492 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4493 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004494 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004495 }
4496}
4497
Douglas Gregore254f902009-02-04 00:32:51 +00004498/// \brief Add function candidates found via argument-dependent lookup
4499/// to the set of overloading candidates.
4500///
4501/// This routine performs argument-dependent name lookup based on the
4502/// given function name (which may also be an operator name) and adds
4503/// all of the overload candidates found by ADL to the overload
4504/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004505void
Douglas Gregore254f902009-02-04 00:32:51 +00004506Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004507 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004508 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004509 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004510 OverloadCandidateSet& CandidateSet,
4511 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004512 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004513
John McCall91f61fc2010-01-26 06:04:06 +00004514 // FIXME: This approach for uniquing ADL results (and removing
4515 // redundant candidates from the set) relies on pointer-equality,
4516 // which means we need to key off the canonical decl. However,
4517 // always going back to the canonical decl might not get us the
4518 // right set of default arguments. What default arguments are
4519 // we supposed to consider on ADL candidates, anyway?
4520
Douglas Gregorcabea402009-09-22 15:41:20 +00004521 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004522 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004523
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004524 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004525 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4526 CandEnd = CandidateSet.end();
4527 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004528 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004529 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004530 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004531 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004532 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004533
4534 // For each of the ADL candidates we found, add it to the overload
4535 // set.
John McCall8fe68082010-01-26 07:16:45 +00004536 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004537 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004539 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004540 continue;
4541
John McCalla0296f72010-03-19 07:35:19 +00004542 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004543 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004544 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004545 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004546 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004547 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004548 }
Douglas Gregore254f902009-02-04 00:32:51 +00004549}
4550
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004551/// isBetterOverloadCandidate - Determines whether the first overload
4552/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004553bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004554Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004555 const OverloadCandidate& Cand2,
4556 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004557 // Define viable functions to be better candidates than non-viable
4558 // functions.
4559 if (!Cand2.Viable)
4560 return Cand1.Viable;
4561 else if (!Cand1.Viable)
4562 return false;
4563
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004564 // C++ [over.match.best]p1:
4565 //
4566 // -- if F is a static member function, ICS1(F) is defined such
4567 // that ICS1(F) is neither better nor worse than ICS1(G) for
4568 // any function G, and, symmetrically, ICS1(G) is neither
4569 // better nor worse than ICS1(F).
4570 unsigned StartArg = 0;
4571 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4572 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004573
Douglas Gregord3cb3562009-07-07 23:38:56 +00004574 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004575 // A viable function F1 is defined to be a better function than another
4576 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004577 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004578 unsigned NumArgs = Cand1.Conversions.size();
4579 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4580 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004581 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004582 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4583 Cand2.Conversions[ArgIdx])) {
4584 case ImplicitConversionSequence::Better:
4585 // Cand1 has a better conversion sequence.
4586 HasBetterConversion = true;
4587 break;
4588
4589 case ImplicitConversionSequence::Worse:
4590 // Cand1 can't be better than Cand2.
4591 return false;
4592
4593 case ImplicitConversionSequence::Indistinguishable:
4594 // Do nothing.
4595 break;
4596 }
4597 }
4598
Mike Stump11289f42009-09-09 15:08:12 +00004599 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004600 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004601 if (HasBetterConversion)
4602 return true;
4603
Mike Stump11289f42009-09-09 15:08:12 +00004604 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004605 // specialization, or, if not that,
4606 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4607 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4608 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004609
4610 // -- F1 and F2 are function template specializations, and the function
4611 // template for F1 is more specialized than the template for F2
4612 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004613 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004614 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4615 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004616 if (FunctionTemplateDecl *BetterTemplate
4617 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4618 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004619 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004620 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4621 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004622 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004623
Douglas Gregora1f013e2008-11-07 22:36:19 +00004624 // -- the context is an initialization by user-defined conversion
4625 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4626 // from the return type of F1 to the destination type (i.e.,
4627 // the type of the entity being initialized) is a better
4628 // conversion sequence than the standard conversion sequence
4629 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004630 if (Cand1.Function && Cand2.Function &&
4631 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004632 isa<CXXConversionDecl>(Cand2.Function)) {
4633 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4634 Cand2.FinalConversion)) {
4635 case ImplicitConversionSequence::Better:
4636 // Cand1 has a better conversion sequence.
4637 return true;
4638
4639 case ImplicitConversionSequence::Worse:
4640 // Cand1 can't be better than Cand2.
4641 return false;
4642
4643 case ImplicitConversionSequence::Indistinguishable:
4644 // Do nothing
4645 break;
4646 }
4647 }
4648
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004649 return false;
4650}
4651
Mike Stump11289f42009-09-09 15:08:12 +00004652/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004653/// within an overload candidate set.
4654///
4655/// \param CandidateSet the set of candidate functions.
4656///
4657/// \param Loc the location of the function name (or operator symbol) for
4658/// which overload resolution occurs.
4659///
Mike Stump11289f42009-09-09 15:08:12 +00004660/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004661/// function, Best points to the candidate function found.
4662///
4663/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004664OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4665 SourceLocation Loc,
4666 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004667 // Find the best viable function.
4668 Best = CandidateSet.end();
4669 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4670 Cand != CandidateSet.end(); ++Cand) {
4671 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004672 if (Best == CandidateSet.end() ||
4673 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004674 Best = Cand;
4675 }
4676 }
4677
4678 // If we didn't find any viable functions, abort.
4679 if (Best == CandidateSet.end())
4680 return OR_No_Viable_Function;
4681
4682 // Make sure that this function is better than every other viable
4683 // function. If not, we have an ambiguity.
4684 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4685 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004686 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004687 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004688 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004689 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004690 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004691 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004692 }
Mike Stump11289f42009-09-09 15:08:12 +00004693
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004694 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004695 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004696 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004697 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004698 return OR_Deleted;
4699
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004700 // C++ [basic.def.odr]p2:
4701 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004702 // when referred to from a potentially-evaluated expression. [Note: this
4703 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004704 // (clause 13), user-defined conversions (12.3.2), allocation function for
4705 // placement new (5.3.4), as well as non-default initialization (8.5).
4706 if (Best->Function)
4707 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004708 return OR_Success;
4709}
4710
John McCall53262c92010-01-12 02:15:36 +00004711namespace {
4712
4713enum OverloadCandidateKind {
4714 oc_function,
4715 oc_method,
4716 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004717 oc_function_template,
4718 oc_method_template,
4719 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004720 oc_implicit_default_constructor,
4721 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004722 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004723};
4724
John McCalle1ac8d12010-01-13 00:25:19 +00004725OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4726 FunctionDecl *Fn,
4727 std::string &Description) {
4728 bool isTemplate = false;
4729
4730 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4731 isTemplate = true;
4732 Description = S.getTemplateArgumentBindingsText(
4733 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4734 }
John McCallfd0b2f82010-01-06 09:43:14 +00004735
4736 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004737 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004738 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004739
John McCall53262c92010-01-12 02:15:36 +00004740 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4741 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004742 }
4743
4744 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4745 // This actually gets spelled 'candidate function' for now, but
4746 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004747 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004748 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004749
4750 assert(Meth->isCopyAssignment()
4751 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004752 return oc_implicit_copy_assignment;
4753 }
4754
John McCalle1ac8d12010-01-13 00:25:19 +00004755 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004756}
4757
4758} // end anonymous namespace
4759
4760// Notes the location of an overload candidate.
4761void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004762 std::string FnDesc;
4763 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4764 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4765 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004766}
4767
John McCall0d1da222010-01-12 00:44:57 +00004768/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4769/// "lead" diagnostic; it will be given two arguments, the source and
4770/// target types of the conversion.
4771void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4772 SourceLocation CaretLoc,
4773 const PartialDiagnostic &PDiag) {
4774 Diag(CaretLoc, PDiag)
4775 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4776 for (AmbiguousConversionSequence::const_iterator
4777 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4778 NoteOverloadCandidate(*I);
4779 }
John McCall12f97bc2010-01-08 04:41:39 +00004780}
4781
John McCall0d1da222010-01-12 00:44:57 +00004782namespace {
4783
John McCall6a61b522010-01-13 09:16:55 +00004784void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4785 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4786 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004787 assert(Cand->Function && "for now, candidate must be a function");
4788 FunctionDecl *Fn = Cand->Function;
4789
4790 // There's a conversion slot for the object argument if this is a
4791 // non-constructor method. Note that 'I' corresponds the
4792 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004793 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004794 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004795 if (I == 0)
4796 isObjectArgument = true;
4797 else
4798 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004799 }
4800
John McCalle1ac8d12010-01-13 00:25:19 +00004801 std::string FnDesc;
4802 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4803
John McCall6a61b522010-01-13 09:16:55 +00004804 Expr *FromExpr = Conv.Bad.FromExpr;
4805 QualType FromTy = Conv.Bad.getFromType();
4806 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004807
John McCallfb7ad0f2010-02-02 02:42:52 +00004808 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004809 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004810 Expr *E = FromExpr->IgnoreParens();
4811 if (isa<UnaryOperator>(E))
4812 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004813 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004814
4815 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4816 << (unsigned) FnKind << FnDesc
4817 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4818 << ToTy << Name << I+1;
4819 return;
4820 }
4821
John McCall6d174642010-01-23 08:10:49 +00004822 // Do some hand-waving analysis to see if the non-viability is due
4823 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004824 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4825 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4826 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4827 CToTy = RT->getPointeeType();
4828 else {
4829 // TODO: detect and diagnose the full richness of const mismatches.
4830 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4831 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4832 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4833 }
4834
4835 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4836 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4837 // It is dumb that we have to do this here.
4838 while (isa<ArrayType>(CFromTy))
4839 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4840 while (isa<ArrayType>(CToTy))
4841 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4842
4843 Qualifiers FromQs = CFromTy.getQualifiers();
4844 Qualifiers ToQs = CToTy.getQualifiers();
4845
4846 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4847 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4848 << (unsigned) FnKind << FnDesc
4849 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4850 << FromTy
4851 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4852 << (unsigned) isObjectArgument << I+1;
4853 return;
4854 }
4855
4856 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4857 assert(CVR && "unexpected qualifiers mismatch");
4858
4859 if (isObjectArgument) {
4860 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4861 << (unsigned) FnKind << FnDesc
4862 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4863 << FromTy << (CVR - 1);
4864 } else {
4865 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4866 << (unsigned) FnKind << FnDesc
4867 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4868 << FromTy << (CVR - 1) << I+1;
4869 }
4870 return;
4871 }
4872
John McCall6d174642010-01-23 08:10:49 +00004873 // Diagnose references or pointers to incomplete types differently,
4874 // since it's far from impossible that the incompleteness triggered
4875 // the failure.
4876 QualType TempFromTy = FromTy.getNonReferenceType();
4877 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4878 TempFromTy = PTy->getPointeeType();
4879 if (TempFromTy->isIncompleteType()) {
4880 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4881 << (unsigned) FnKind << FnDesc
4882 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4883 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4884 return;
4885 }
4886
John McCall47000992010-01-14 03:28:57 +00004887 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004888 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4889 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004890 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004891 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004892}
4893
4894void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4895 unsigned NumFormalArgs) {
4896 // TODO: treat calls to a missing default constructor as a special case
4897
4898 FunctionDecl *Fn = Cand->Function;
4899 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4900
4901 unsigned MinParams = Fn->getMinRequiredArguments();
4902
4903 // at least / at most / exactly
4904 unsigned mode, modeCount;
4905 if (NumFormalArgs < MinParams) {
4906 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4907 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4908 mode = 0; // "at least"
4909 else
4910 mode = 2; // "exactly"
4911 modeCount = MinParams;
4912 } else {
4913 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4914 if (MinParams != FnTy->getNumArgs())
4915 mode = 1; // "at most"
4916 else
4917 mode = 2; // "exactly"
4918 modeCount = FnTy->getNumArgs();
4919 }
4920
4921 std::string Description;
4922 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4923
4924 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4925 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004926}
4927
John McCall8b9ed552010-02-01 18:53:26 +00004928/// Diagnose a failed template-argument deduction.
4929void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4930 Expr **Args, unsigned NumArgs) {
4931 FunctionDecl *Fn = Cand->Function; // pattern
4932
4933 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4934 Cand->DeductionFailure.TemplateParameter);
4935
4936 switch (Cand->DeductionFailure.Result) {
4937 case Sema::TDK_Success:
4938 llvm_unreachable("TDK_success while diagnosing bad deduction");
4939
4940 case Sema::TDK_Incomplete: {
4941 NamedDecl *ParamD;
4942 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4943 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4944 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4945 assert(ParamD && "no parameter found for incomplete deduction result");
4946 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4947 << ParamD->getDeclName();
4948 return;
4949 }
4950
4951 // TODO: diagnose these individually, then kill off
4952 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4953 case Sema::TDK_InstantiationDepth:
4954 case Sema::TDK_Inconsistent:
4955 case Sema::TDK_InconsistentQuals:
4956 case Sema::TDK_SubstitutionFailure:
4957 case Sema::TDK_NonDeducedMismatch:
4958 case Sema::TDK_TooManyArguments:
4959 case Sema::TDK_TooFewArguments:
4960 case Sema::TDK_InvalidExplicitArguments:
4961 case Sema::TDK_FailedOverloadResolution:
4962 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4963 return;
4964 }
4965}
4966
4967/// Generates a 'note' diagnostic for an overload candidate. We've
4968/// already generated a primary error at the call site.
4969///
4970/// It really does need to be a single diagnostic with its caret
4971/// pointed at the candidate declaration. Yes, this creates some
4972/// major challenges of technical writing. Yes, this makes pointing
4973/// out problems with specific arguments quite awkward. It's still
4974/// better than generating twenty screens of text for every failed
4975/// overload.
4976///
4977/// It would be great to be able to express per-candidate problems
4978/// more richly for those diagnostic clients that cared, but we'd
4979/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004980void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4981 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004982 FunctionDecl *Fn = Cand->Function;
4983
John McCall12f97bc2010-01-08 04:41:39 +00004984 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004985 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004986 std::string FnDesc;
4987 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004988
4989 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004990 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004991 return;
John McCall12f97bc2010-01-08 04:41:39 +00004992 }
4993
John McCalle1ac8d12010-01-13 00:25:19 +00004994 // We don't really have anything else to say about viable candidates.
4995 if (Cand->Viable) {
4996 S.NoteOverloadCandidate(Fn);
4997 return;
4998 }
John McCall0d1da222010-01-12 00:44:57 +00004999
John McCall6a61b522010-01-13 09:16:55 +00005000 switch (Cand->FailureKind) {
5001 case ovl_fail_too_many_arguments:
5002 case ovl_fail_too_few_arguments:
5003 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005004
John McCall6a61b522010-01-13 09:16:55 +00005005 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005006 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5007
John McCallfe796dd2010-01-23 05:17:32 +00005008 case ovl_fail_trivial_conversion:
5009 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005010 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005011 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005012
John McCall65eb8792010-02-25 01:37:24 +00005013 case ovl_fail_bad_conversion: {
5014 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5015 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005016 if (Cand->Conversions[I].isBad())
5017 return DiagnoseBadConversion(S, Cand, I);
5018
5019 // FIXME: this currently happens when we're called from SemaInit
5020 // when user-conversion overload fails. Figure out how to handle
5021 // those conditions and diagnose them well.
5022 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005023 }
John McCall65eb8792010-02-25 01:37:24 +00005024 }
John McCalld3224162010-01-08 00:58:21 +00005025}
5026
5027void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5028 // Desugar the type of the surrogate down to a function type,
5029 // retaining as many typedefs as possible while still showing
5030 // the function type (and, therefore, its parameter types).
5031 QualType FnType = Cand->Surrogate->getConversionType();
5032 bool isLValueReference = false;
5033 bool isRValueReference = false;
5034 bool isPointer = false;
5035 if (const LValueReferenceType *FnTypeRef =
5036 FnType->getAs<LValueReferenceType>()) {
5037 FnType = FnTypeRef->getPointeeType();
5038 isLValueReference = true;
5039 } else if (const RValueReferenceType *FnTypeRef =
5040 FnType->getAs<RValueReferenceType>()) {
5041 FnType = FnTypeRef->getPointeeType();
5042 isRValueReference = true;
5043 }
5044 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5045 FnType = FnTypePtr->getPointeeType();
5046 isPointer = true;
5047 }
5048 // Desugar down to a function type.
5049 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5050 // Reconstruct the pointer/reference as appropriate.
5051 if (isPointer) FnType = S.Context.getPointerType(FnType);
5052 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5053 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5054
5055 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5056 << FnType;
5057}
5058
5059void NoteBuiltinOperatorCandidate(Sema &S,
5060 const char *Opc,
5061 SourceLocation OpLoc,
5062 OverloadCandidate *Cand) {
5063 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5064 std::string TypeStr("operator");
5065 TypeStr += Opc;
5066 TypeStr += "(";
5067 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5068 if (Cand->Conversions.size() == 1) {
5069 TypeStr += ")";
5070 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5071 } else {
5072 TypeStr += ", ";
5073 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5074 TypeStr += ")";
5075 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5076 }
5077}
5078
5079void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5080 OverloadCandidate *Cand) {
5081 unsigned NoOperands = Cand->Conversions.size();
5082 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5083 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005084 if (ICS.isBad()) break; // all meaningless after first invalid
5085 if (!ICS.isAmbiguous()) continue;
5086
5087 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005088 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005089 }
5090}
5091
John McCall3712d9e2010-01-15 23:32:50 +00005092SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5093 if (Cand->Function)
5094 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005095 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005096 return Cand->Surrogate->getLocation();
5097 return SourceLocation();
5098}
5099
John McCallad2587a2010-01-12 00:48:53 +00005100struct CompareOverloadCandidatesForDisplay {
5101 Sema &S;
5102 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005103
5104 bool operator()(const OverloadCandidate *L,
5105 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005106 // Fast-path this check.
5107 if (L == R) return false;
5108
John McCall12f97bc2010-01-08 04:41:39 +00005109 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005110 if (L->Viable) {
5111 if (!R->Viable) return true;
5112
5113 // TODO: introduce a tri-valued comparison for overload
5114 // candidates. Would be more worthwhile if we had a sort
5115 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005116 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5117 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005118 } else if (R->Viable)
5119 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005120
John McCall3712d9e2010-01-15 23:32:50 +00005121 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005122
John McCall3712d9e2010-01-15 23:32:50 +00005123 // Criteria by which we can sort non-viable candidates:
5124 if (!L->Viable) {
5125 // 1. Arity mismatches come after other candidates.
5126 if (L->FailureKind == ovl_fail_too_many_arguments ||
5127 L->FailureKind == ovl_fail_too_few_arguments)
5128 return false;
5129 if (R->FailureKind == ovl_fail_too_many_arguments ||
5130 R->FailureKind == ovl_fail_too_few_arguments)
5131 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005132
John McCallfe796dd2010-01-23 05:17:32 +00005133 // 2. Bad conversions come first and are ordered by the number
5134 // of bad conversions and quality of good conversions.
5135 if (L->FailureKind == ovl_fail_bad_conversion) {
5136 if (R->FailureKind != ovl_fail_bad_conversion)
5137 return true;
5138
5139 // If there's any ordering between the defined conversions...
5140 // FIXME: this might not be transitive.
5141 assert(L->Conversions.size() == R->Conversions.size());
5142
5143 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005144 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5145 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005146 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5147 R->Conversions[I])) {
5148 case ImplicitConversionSequence::Better:
5149 leftBetter++;
5150 break;
5151
5152 case ImplicitConversionSequence::Worse:
5153 leftBetter--;
5154 break;
5155
5156 case ImplicitConversionSequence::Indistinguishable:
5157 break;
5158 }
5159 }
5160 if (leftBetter > 0) return true;
5161 if (leftBetter < 0) return false;
5162
5163 } else if (R->FailureKind == ovl_fail_bad_conversion)
5164 return false;
5165
John McCall3712d9e2010-01-15 23:32:50 +00005166 // TODO: others?
5167 }
5168
5169 // Sort everything else by location.
5170 SourceLocation LLoc = GetLocationForCandidate(L);
5171 SourceLocation RLoc = GetLocationForCandidate(R);
5172
5173 // Put candidates without locations (e.g. builtins) at the end.
5174 if (LLoc.isInvalid()) return false;
5175 if (RLoc.isInvalid()) return true;
5176
5177 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005178 }
5179};
5180
John McCallfe796dd2010-01-23 05:17:32 +00005181/// CompleteNonViableCandidate - Normally, overload resolution only
5182/// computes up to the first
5183void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5184 Expr **Args, unsigned NumArgs) {
5185 assert(!Cand->Viable);
5186
5187 // Don't do anything on failures other than bad conversion.
5188 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5189
5190 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005191 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005192 unsigned ConvCount = Cand->Conversions.size();
5193 while (true) {
5194 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5195 ConvIdx++;
5196 if (Cand->Conversions[ConvIdx - 1].isBad())
5197 break;
5198 }
5199
5200 if (ConvIdx == ConvCount)
5201 return;
5202
John McCall65eb8792010-02-25 01:37:24 +00005203 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5204 "remaining conversion is initialized?");
5205
Douglas Gregoradc7a702010-04-16 17:45:54 +00005206 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005207 // operation somehow.
5208 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005209
5210 const FunctionProtoType* Proto;
5211 unsigned ArgIdx = ConvIdx;
5212
5213 if (Cand->IsSurrogate) {
5214 QualType ConvType
5215 = Cand->Surrogate->getConversionType().getNonReferenceType();
5216 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5217 ConvType = ConvPtrType->getPointeeType();
5218 Proto = ConvType->getAs<FunctionProtoType>();
5219 ArgIdx--;
5220 } else if (Cand->Function) {
5221 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5222 if (isa<CXXMethodDecl>(Cand->Function) &&
5223 !isa<CXXConstructorDecl>(Cand->Function))
5224 ArgIdx--;
5225 } else {
5226 // Builtin binary operator with a bad first conversion.
5227 assert(ConvCount <= 3);
5228 for (; ConvIdx != ConvCount; ++ConvIdx)
5229 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005230 = TryCopyInitialization(S, Args[ConvIdx],
5231 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5232 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005233 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005234 return;
5235 }
5236
5237 // Fill in the rest of the conversions.
5238 unsigned NumArgsInProto = Proto->getNumArgs();
5239 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5240 if (ArgIdx < NumArgsInProto)
5241 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005242 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5243 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005244 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005245 else
5246 Cand->Conversions[ConvIdx].setEllipsis();
5247 }
5248}
5249
John McCalld3224162010-01-08 00:58:21 +00005250} // end anonymous namespace
5251
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005252/// PrintOverloadCandidates - When overload resolution fails, prints
5253/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005254/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005255void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005256Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005257 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005258 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005259 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005260 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005261 // Sort the candidates by viability and position. Sorting directly would
5262 // be prohibitive, so we make a set of pointers and sort those.
5263 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5264 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5265 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5266 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005267 Cand != LastCand; ++Cand) {
5268 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005269 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005270 else if (OCD == OCD_AllCandidates) {
5271 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5272 Cands.push_back(Cand);
5273 }
5274 }
5275
John McCallad2587a2010-01-12 00:48:53 +00005276 std::sort(Cands.begin(), Cands.end(),
5277 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005278
John McCall0d1da222010-01-12 00:44:57 +00005279 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005280
John McCall12f97bc2010-01-08 04:41:39 +00005281 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5282 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5283 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005284
John McCalld3224162010-01-08 00:58:21 +00005285 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005286 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005287 else if (Cand->IsSurrogate)
5288 NoteSurrogateCandidate(*this, Cand);
5289
5290 // This a builtin candidate. We do not, in general, want to list
5291 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005292 else if (Cand->Viable) {
5293 // Generally we only see ambiguities including viable builtin
5294 // operators if overload resolution got screwed up by an
5295 // ambiguous user-defined conversion.
5296 //
5297 // FIXME: It's quite possible for different conversions to see
5298 // different ambiguities, though.
5299 if (!ReportedAmbiguousConversions) {
5300 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5301 ReportedAmbiguousConversions = true;
5302 }
John McCalld3224162010-01-08 00:58:21 +00005303
John McCall0d1da222010-01-12 00:44:57 +00005304 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005305 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005306 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005307 }
5308}
5309
John McCalla0296f72010-03-19 07:35:19 +00005310static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005311 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005312 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005313
John McCalla0296f72010-03-19 07:35:19 +00005314 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005315}
5316
Douglas Gregorcd695e52008-11-10 20:40:00 +00005317/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5318/// an overloaded function (C++ [over.over]), where @p From is an
5319/// expression with overloaded function type and @p ToType is the type
5320/// we're trying to resolve to. For example:
5321///
5322/// @code
5323/// int f(double);
5324/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005325///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005326/// int (*pfd)(double) = f; // selects f(double)
5327/// @endcode
5328///
5329/// This routine returns the resulting FunctionDecl if it could be
5330/// resolved, and NULL otherwise. When @p Complain is true, this
5331/// routine will emit diagnostics if there is an error.
5332FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005333Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005334 bool Complain,
5335 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005336 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005337 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005338 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005339 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005340 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005341 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005342 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005343 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005344 FunctionType = MemTypePtr->getPointeeType();
5345 IsMember = true;
5346 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005347
Douglas Gregorcd695e52008-11-10 20:40:00 +00005348 // C++ [over.over]p1:
5349 // [...] [Note: any redundant set of parentheses surrounding the
5350 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005351 // C++ [over.over]p1:
5352 // [...] The overloaded function name can be preceded by the &
5353 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005354 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5355 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5356 if (OvlExpr->hasExplicitTemplateArgs()) {
5357 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5358 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005359 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005360
5361 // We expect a pointer or reference to function, or a function pointer.
5362 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5363 if (!FunctionType->isFunctionType()) {
5364 if (Complain)
5365 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5366 << OvlExpr->getName() << ToType;
5367
5368 return 0;
5369 }
5370
5371 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005372
Douglas Gregorcd695e52008-11-10 20:40:00 +00005373 // Look through all of the overloaded functions, searching for one
5374 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005375 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005376 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5377
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005378 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005379 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5380 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005381 // Look through any using declarations to find the underlying function.
5382 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5383
Douglas Gregorcd695e52008-11-10 20:40:00 +00005384 // C++ [over.over]p3:
5385 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005386 // targets of type "pointer-to-function" or "reference-to-function."
5387 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005388 // type "pointer-to-member-function."
5389 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005390
Mike Stump11289f42009-09-09 15:08:12 +00005391 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005392 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005393 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005394 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005395 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005396 // static when converting to member pointer.
5397 if (Method->isStatic() == IsMember)
5398 continue;
5399 } else if (IsMember)
5400 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005401
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005402 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005403 // If the name is a function template, template argument deduction is
5404 // done (14.8.2.2), and if the argument deduction succeeds, the
5405 // resulting template argument list is used to generate a single
5406 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005407 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005408 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005409 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005410 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005411 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005412 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005413 FunctionType, Specialization, Info)) {
5414 // FIXME: make a note of the failed deduction for diagnostics.
5415 (void)Result;
5416 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005417 // FIXME: If the match isn't exact, shouldn't we just drop this as
5418 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005419 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005420 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005421 Matches.push_back(std::make_pair(I.getPair(),
5422 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005423 }
John McCalld14a8642009-11-21 08:51:07 +00005424
5425 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005426 }
Mike Stump11289f42009-09-09 15:08:12 +00005427
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005428 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005429 // Skip non-static functions when converting to pointer, and static
5430 // when converting to member pointer.
5431 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005432 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005433
5434 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005435 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005436 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005437 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005438 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005439
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005440 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005441 QualType ResultTy;
5442 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5443 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5444 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005445 Matches.push_back(std::make_pair(I.getPair(),
5446 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005447 FoundNonTemplateFunction = true;
5448 }
Mike Stump11289f42009-09-09 15:08:12 +00005449 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005450 }
5451
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005452 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005453 if (Matches.empty()) {
5454 if (Complain) {
5455 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5456 << OvlExpr->getName() << FunctionType;
5457 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5458 E = OvlExpr->decls_end();
5459 I != E; ++I)
5460 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5461 NoteOverloadCandidate(F);
5462 }
5463
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005464 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005465 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005466 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005467 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005468 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005469 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005470 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005471 return Result;
5472 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005473
5474 // C++ [over.over]p4:
5475 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005476 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005477 // [...] and any given function template specialization F1 is
5478 // eliminated if the set contains a second function template
5479 // specialization whose function template is more specialized
5480 // than the function template of F1 according to the partial
5481 // ordering rules of 14.5.5.2.
5482
5483 // The algorithm specified above is quadratic. We instead use a
5484 // two-pass algorithm (similar to the one used to identify the
5485 // best viable function in an overload set) that identifies the
5486 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005487
5488 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5489 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5490 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005491
5492 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005493 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005494 TPOC_Other, From->getLocStart(),
5495 PDiag(),
5496 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005497 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005498 PDiag(diag::note_ovl_candidate)
5499 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005500 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005501 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005502 FoundResult = Matches[Result - MatchesCopy.begin()].first;
5503 if (Complain)
5504 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00005505 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005506 }
Mike Stump11289f42009-09-09 15:08:12 +00005507
Douglas Gregorfae1d712009-09-26 03:56:17 +00005508 // [...] any function template specializations in the set are
5509 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005510 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005511 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005512 ++I;
5513 else {
John McCalla0296f72010-03-19 07:35:19 +00005514 Matches[I] = Matches[--N];
5515 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005516 }
5517 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005518
Mike Stump11289f42009-09-09 15:08:12 +00005519 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005520 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005521 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005522 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005523 FoundResult = Matches[0].first;
John McCall58cc69d2010-01-27 01:50:18 +00005524 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00005525 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5526 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005527 }
Mike Stump11289f42009-09-09 15:08:12 +00005528
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005529 // FIXME: We should probably return the same thing that BestViableFunction
5530 // returns (even if we issue the diagnostics here).
5531 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005532 << Matches[0].second->getDeclName();
5533 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5534 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005535 return 0;
5536}
5537
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005538/// \brief Given an expression that refers to an overloaded function, try to
5539/// resolve that overloaded function expression down to a single function.
5540///
5541/// This routine can only resolve template-ids that refer to a single function
5542/// template, where that template-id refers to a single template whose template
5543/// arguments are either provided by the template-id or have defaults,
5544/// as described in C++0x [temp.arg.explicit]p3.
5545FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5546 // C++ [over.over]p1:
5547 // [...] [Note: any redundant set of parentheses surrounding the
5548 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005549 // C++ [over.over]p1:
5550 // [...] The overloaded function name can be preceded by the &
5551 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005552
5553 if (From->getType() != Context.OverloadTy)
5554 return 0;
5555
5556 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005557
5558 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005559 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005560 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005561
5562 TemplateArgumentListInfo ExplicitTemplateArgs;
5563 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005564
5565 // Look through all of the overloaded functions, searching for one
5566 // whose type matches exactly.
5567 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005568 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5569 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005570 // C++0x [temp.arg.explicit]p3:
5571 // [...] In contexts where deduction is done and fails, or in contexts
5572 // where deduction is not done, if a template argument list is
5573 // specified and it, along with any default template arguments,
5574 // identifies a single function template specialization, then the
5575 // template-id is an lvalue for the function template specialization.
5576 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5577
5578 // C++ [over.over]p2:
5579 // If the name is a function template, template argument deduction is
5580 // done (14.8.2.2), and if the argument deduction succeeds, the
5581 // resulting template argument list is used to generate a single
5582 // function template specialization, which is added to the set of
5583 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005584 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005585 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005586 if (TemplateDeductionResult Result
5587 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5588 Specialization, Info)) {
5589 // FIXME: make a note of the failed deduction for diagnostics.
5590 (void)Result;
5591 continue;
5592 }
5593
5594 // Multiple matches; we can't resolve to a single declaration.
5595 if (Matched)
5596 return 0;
5597
5598 Matched = Specialization;
5599 }
5600
5601 return Matched;
5602}
5603
Douglas Gregorcabea402009-09-22 15:41:20 +00005604/// \brief Add a single candidate to the overload set.
5605static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005606 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005607 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005608 Expr **Args, unsigned NumArgs,
5609 OverloadCandidateSet &CandidateSet,
5610 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005611 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005612 if (isa<UsingShadowDecl>(Callee))
5613 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5614
Douglas Gregorcabea402009-09-22 15:41:20 +00005615 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005616 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005617 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005618 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005619 return;
John McCalld14a8642009-11-21 08:51:07 +00005620 }
5621
5622 if (FunctionTemplateDecl *FuncTemplate
5623 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005624 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5625 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005626 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005627 return;
5628 }
5629
5630 assert(false && "unhandled case in overloaded call candidate");
5631
5632 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005633}
5634
5635/// \brief Add the overload candidates named by callee and/or found by argument
5636/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005637void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005638 Expr **Args, unsigned NumArgs,
5639 OverloadCandidateSet &CandidateSet,
5640 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005641
5642#ifndef NDEBUG
5643 // Verify that ArgumentDependentLookup is consistent with the rules
5644 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005645 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005646 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5647 // and let Y be the lookup set produced by argument dependent
5648 // lookup (defined as follows). If X contains
5649 //
5650 // -- a declaration of a class member, or
5651 //
5652 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005653 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005654 //
5655 // -- a declaration that is neither a function or a function
5656 // template
5657 //
5658 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005659
John McCall57500772009-12-16 12:17:52 +00005660 if (ULE->requiresADL()) {
5661 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5662 E = ULE->decls_end(); I != E; ++I) {
5663 assert(!(*I)->getDeclContext()->isRecord());
5664 assert(isa<UsingShadowDecl>(*I) ||
5665 !(*I)->getDeclContext()->isFunctionOrMethod());
5666 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005667 }
5668 }
5669#endif
5670
John McCall57500772009-12-16 12:17:52 +00005671 // It would be nice to avoid this copy.
5672 TemplateArgumentListInfo TABuffer;
5673 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5674 if (ULE->hasExplicitTemplateArgs()) {
5675 ULE->copyTemplateArgumentsInto(TABuffer);
5676 ExplicitTemplateArgs = &TABuffer;
5677 }
5678
5679 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5680 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005681 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005682 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005683 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005684
John McCall57500772009-12-16 12:17:52 +00005685 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005686 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5687 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005688 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005689 CandidateSet,
5690 PartialOverloading);
5691}
John McCalld681c392009-12-16 08:11:27 +00005692
John McCall57500772009-12-16 12:17:52 +00005693static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5694 Expr **Args, unsigned NumArgs) {
5695 Fn->Destroy(SemaRef.Context);
5696 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5697 Args[Arg]->Destroy(SemaRef.Context);
5698 return SemaRef.ExprError();
5699}
5700
John McCalld681c392009-12-16 08:11:27 +00005701/// Attempts to recover from a call where no functions were found.
5702///
5703/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005704static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005705BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005706 UnresolvedLookupExpr *ULE,
5707 SourceLocation LParenLoc,
5708 Expr **Args, unsigned NumArgs,
5709 SourceLocation *CommaLocs,
5710 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005711
5712 CXXScopeSpec SS;
5713 if (ULE->getQualifier()) {
5714 SS.setScopeRep(ULE->getQualifier());
5715 SS.setRange(ULE->getQualifierRange());
5716 }
5717
John McCall57500772009-12-16 12:17:52 +00005718 TemplateArgumentListInfo TABuffer;
5719 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5720 if (ULE->hasExplicitTemplateArgs()) {
5721 ULE->copyTemplateArgumentsInto(TABuffer);
5722 ExplicitTemplateArgs = &TABuffer;
5723 }
5724
John McCalld681c392009-12-16 08:11:27 +00005725 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5726 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005727 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005728 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005729
John McCall57500772009-12-16 12:17:52 +00005730 assert(!R.empty() && "lookup results empty despite recovery");
5731
5732 // Build an implicit member call if appropriate. Just drop the
5733 // casts and such from the call, we don't really care.
5734 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5735 if ((*R.begin())->isCXXClassMember())
5736 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5737 else if (ExplicitTemplateArgs)
5738 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5739 else
5740 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5741
5742 if (NewFn.isInvalid())
5743 return Destroy(SemaRef, Fn, Args, NumArgs);
5744
5745 Fn->Destroy(SemaRef.Context);
5746
5747 // This shouldn't cause an infinite loop because we're giving it
5748 // an expression with non-empty lookup results, which should never
5749 // end up here.
5750 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5751 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5752 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005753}
Douglas Gregorcabea402009-09-22 15:41:20 +00005754
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005755/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005756/// (which eventually refers to the declaration Func) and the call
5757/// arguments Args/NumArgs, attempt to resolve the function call down
5758/// to a specific function. If overload resolution succeeds, returns
5759/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005760/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005761/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005762Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005763Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005764 SourceLocation LParenLoc,
5765 Expr **Args, unsigned NumArgs,
5766 SourceLocation *CommaLocs,
5767 SourceLocation RParenLoc) {
5768#ifndef NDEBUG
5769 if (ULE->requiresADL()) {
5770 // To do ADL, we must have found an unqualified name.
5771 assert(!ULE->getQualifier() && "qualified name with ADL");
5772
5773 // We don't perform ADL for implicit declarations of builtins.
5774 // Verify that this was correctly set up.
5775 FunctionDecl *F;
5776 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5777 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5778 F->getBuiltinID() && F->isImplicit())
5779 assert(0 && "performing ADL for builtin");
5780
5781 // We don't perform ADL in C.
5782 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5783 }
5784#endif
5785
John McCallbc077cf2010-02-08 23:07:23 +00005786 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005787
John McCall57500772009-12-16 12:17:52 +00005788 // Add the functions denoted by the callee to the set of candidate
5789 // functions, including those from argument-dependent lookup.
5790 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005791
5792 // If we found nothing, try to recover.
5793 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5794 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005795 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005796 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00005797 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005798
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005799 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005800 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005801 case OR_Success: {
5802 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00005803 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall16df1e52010-03-30 21:47:33 +00005804 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00005805 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5806 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005807
5808 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005809 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005810 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005811 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005812 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005813 break;
5814
5815 case OR_Ambiguous:
5816 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005817 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005818 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005819 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005820
5821 case OR_Deleted:
5822 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5823 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005824 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005825 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005826 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005827 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005828 }
5829
5830 // Overload resolution failed. Destroy all of the subexpressions and
5831 // return NULL.
5832 Fn->Destroy(Context);
5833 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5834 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005835 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005836}
5837
John McCall4c4c1df2010-01-26 03:27:55 +00005838static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005839 return Functions.size() > 1 ||
5840 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5841}
5842
Douglas Gregor084d8552009-03-13 23:49:33 +00005843/// \brief Create a unary operation that may resolve to an overloaded
5844/// operator.
5845///
5846/// \param OpLoc The location of the operator itself (e.g., '*').
5847///
5848/// \param OpcIn The UnaryOperator::Opcode that describes this
5849/// operator.
5850///
5851/// \param Functions The set of non-member functions that will be
5852/// considered by overload resolution. The caller needs to build this
5853/// set based on the context using, e.g.,
5854/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5855/// set should not contain any member functions; those will be added
5856/// by CreateOverloadedUnaryOp().
5857///
5858/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005859Sema::OwningExprResult
5860Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5861 const UnresolvedSetImpl &Fns,
5862 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005863 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5864 Expr *Input = (Expr *)input.get();
5865
5866 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5867 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5868 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5869
5870 Expr *Args[2] = { Input, 0 };
5871 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005872
Douglas Gregor084d8552009-03-13 23:49:33 +00005873 // For post-increment and post-decrement, add the implicit '0' as
5874 // the second argument, so that we know this is a post-increment or
5875 // post-decrement.
5876 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5877 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005878 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005879 SourceLocation());
5880 NumArgs = 2;
5881 }
5882
5883 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005884 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005885 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005886 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005887 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005888 /*ADL*/ true, IsOverloaded(Fns));
5889 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005890
Douglas Gregor084d8552009-03-13 23:49:33 +00005891 input.release();
5892 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5893 &Args[0], NumArgs,
5894 Context.DependentTy,
5895 OpLoc));
5896 }
5897
5898 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005899 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005900
5901 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005902 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005903
5904 // Add operator candidates that are member functions.
5905 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5906
John McCall4c4c1df2010-01-26 03:27:55 +00005907 // Add candidates from ADL.
5908 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005909 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005910 /*ExplicitTemplateArgs*/ 0,
5911 CandidateSet);
5912
Douglas Gregor084d8552009-03-13 23:49:33 +00005913 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005914 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005915
5916 // Perform overload resolution.
5917 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005918 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005919 case OR_Success: {
5920 // We found a built-in operator or an overloaded operator.
5921 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005922
Douglas Gregor084d8552009-03-13 23:49:33 +00005923 if (FnDecl) {
5924 // We matched an overloaded operator. Build a call to that
5925 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005926
Douglas Gregor084d8552009-03-13 23:49:33 +00005927 // Convert the arguments.
5928 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00005929 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00005930
John McCall16df1e52010-03-30 21:47:33 +00005931 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5932 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005933 return ExprError();
5934 } else {
5935 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005936 OwningExprResult InputInit
5937 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005938 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005939 SourceLocation(),
5940 move(input));
5941 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005942 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005943
Douglas Gregore6600372009-12-23 17:40:29 +00005944 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005945 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005946 }
5947
5948 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005949 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005950
Douglas Gregor084d8552009-03-13 23:49:33 +00005951 // Build the actual expression node.
5952 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5953 SourceLocation());
5954 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005955
Douglas Gregor084d8552009-03-13 23:49:33 +00005956 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005957 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005958 ExprOwningPtr<CallExpr> TheCall(this,
5959 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005960 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005961
5962 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5963 FnDecl))
5964 return ExprError();
5965
5966 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005967 } else {
5968 // We matched a built-in operator. Convert the arguments, then
5969 // break out so that we will build the appropriate built-in
5970 // operator node.
5971 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005972 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005973 return ExprError();
5974
5975 break;
5976 }
5977 }
5978
5979 case OR_No_Viable_Function:
5980 // No viable function; fall through to handling this as a
5981 // built-in operator, which will produce an error message for us.
5982 break;
5983
5984 case OR_Ambiguous:
5985 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5986 << UnaryOperator::getOpcodeStr(Opc)
5987 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005988 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005989 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005990 return ExprError();
5991
5992 case OR_Deleted:
5993 Diag(OpLoc, diag::err_ovl_deleted_oper)
5994 << Best->Function->isDeleted()
5995 << UnaryOperator::getOpcodeStr(Opc)
5996 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005997 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005998 return ExprError();
5999 }
6000
6001 // Either we found no viable overloaded operator or we matched a
6002 // built-in operator. In either case, fall through to trying to
6003 // build a built-in operation.
6004 input.release();
6005 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6006}
6007
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006008/// \brief Create a binary operation that may resolve to an overloaded
6009/// operator.
6010///
6011/// \param OpLoc The location of the operator itself (e.g., '+').
6012///
6013/// \param OpcIn The BinaryOperator::Opcode that describes this
6014/// operator.
6015///
6016/// \param Functions The set of non-member functions that will be
6017/// considered by overload resolution. The caller needs to build this
6018/// set based on the context using, e.g.,
6019/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6020/// set should not contain any member functions; those will be added
6021/// by CreateOverloadedBinOp().
6022///
6023/// \param LHS Left-hand argument.
6024/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006025Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006026Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006027 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006028 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006029 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006030 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006031 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006032
6033 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6034 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6035 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6036
6037 // If either side is type-dependent, create an appropriate dependent
6038 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006039 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006040 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006041 // If there are no functions to store, just build a dependent
6042 // BinaryOperator or CompoundAssignment.
6043 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6044 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6045 Context.DependentTy, OpLoc));
6046
6047 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6048 Context.DependentTy,
6049 Context.DependentTy,
6050 Context.DependentTy,
6051 OpLoc));
6052 }
John McCall4c4c1df2010-01-26 03:27:55 +00006053
6054 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006055 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006056 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006057 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006058 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006059 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006060
John McCall4c4c1df2010-01-26 03:27:55 +00006061 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006062 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006063 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006064 Context.DependentTy,
6065 OpLoc));
6066 }
6067
6068 // If this is the .* operator, which is not overloadable, just
6069 // create a built-in binary operator.
6070 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006071 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006072
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006073 // If this is the assignment operator, we only perform overload resolution
6074 // if the left-hand side is a class or enumeration type. This is actually
6075 // a hack. The standard requires that we do overload resolution between the
6076 // various built-in candidates, but as DR507 points out, this can lead to
6077 // problems. So we do it this way, which pretty much follows what GCC does.
6078 // Note that we go the traditional code path for compound assignment forms.
6079 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006080 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006081
Douglas Gregor084d8552009-03-13 23:49:33 +00006082 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006083 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006084
6085 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006086 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006087
6088 // Add operator candidates that are member functions.
6089 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6090
John McCall4c4c1df2010-01-26 03:27:55 +00006091 // Add candidates from ADL.
6092 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6093 Args, 2,
6094 /*ExplicitTemplateArgs*/ 0,
6095 CandidateSet);
6096
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006097 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006098 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006099
6100 // Perform overload resolution.
6101 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006102 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006103 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006104 // We found a built-in operator or an overloaded operator.
6105 FunctionDecl *FnDecl = Best->Function;
6106
6107 if (FnDecl) {
6108 // We matched an overloaded operator. Build a call to that
6109 // operator.
6110
6111 // Convert the arguments.
6112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006113 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006114 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006115
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006116 OwningExprResult Arg1
6117 = PerformCopyInitialization(
6118 InitializedEntity::InitializeParameter(
6119 FnDecl->getParamDecl(0)),
6120 SourceLocation(),
6121 Owned(Args[1]));
6122 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006123 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006124
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006125 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006126 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006127 return ExprError();
6128
6129 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006130 } else {
6131 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006132 OwningExprResult Arg0
6133 = PerformCopyInitialization(
6134 InitializedEntity::InitializeParameter(
6135 FnDecl->getParamDecl(0)),
6136 SourceLocation(),
6137 Owned(Args[0]));
6138 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006139 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006140
6141 OwningExprResult Arg1
6142 = PerformCopyInitialization(
6143 InitializedEntity::InitializeParameter(
6144 FnDecl->getParamDecl(1)),
6145 SourceLocation(),
6146 Owned(Args[1]));
6147 if (Arg1.isInvalid())
6148 return ExprError();
6149 Args[0] = LHS = Arg0.takeAs<Expr>();
6150 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006151 }
6152
6153 // Determine the result type
6154 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006155 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006156 ResultTy = ResultTy.getNonReferenceType();
6157
6158 // Build the actual expression node.
6159 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006160 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006161 UsualUnaryConversions(FnExpr);
6162
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006163 ExprOwningPtr<CXXOperatorCallExpr>
6164 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6165 Args, 2, ResultTy,
6166 OpLoc));
6167
6168 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6169 FnDecl))
6170 return ExprError();
6171
6172 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006173 } else {
6174 // We matched a built-in operator. Convert the arguments, then
6175 // break out so that we will build the appropriate built-in
6176 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006177 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006178 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006179 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006180 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006181 return ExprError();
6182
6183 break;
6184 }
6185 }
6186
Douglas Gregor66950a32009-09-30 21:46:01 +00006187 case OR_No_Viable_Function: {
6188 // C++ [over.match.oper]p9:
6189 // If the operator is the operator , [...] and there are no
6190 // viable functions, then the operator is assumed to be the
6191 // built-in operator and interpreted according to clause 5.
6192 if (Opc == BinaryOperator::Comma)
6193 break;
6194
Sebastian Redl027de2a2009-05-21 11:50:50 +00006195 // For class as left operand for assignment or compound assigment operator
6196 // do not fall through to handling in built-in, but report that no overloaded
6197 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006198 OwningExprResult Result = ExprError();
6199 if (Args[0]->getType()->isRecordType() &&
6200 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006201 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6202 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006203 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006204 } else {
6205 // No viable function; try to create a built-in operation, which will
6206 // produce an error. Then, show the non-viable candidates.
6207 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006208 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006209 assert(Result.isInvalid() &&
6210 "C++ binary operator overloading is missing candidates!");
6211 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006212 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006213 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006214 return move(Result);
6215 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006216
6217 case OR_Ambiguous:
6218 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6219 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006220 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006221 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006222 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006223 return ExprError();
6224
6225 case OR_Deleted:
6226 Diag(OpLoc, diag::err_ovl_deleted_oper)
6227 << Best->Function->isDeleted()
6228 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006229 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006230 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006231 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006232 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006233
Douglas Gregor66950a32009-09-30 21:46:01 +00006234 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006235 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006236}
6237
Sebastian Redladba46e2009-10-29 20:17:01 +00006238Action::OwningExprResult
6239Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6240 SourceLocation RLoc,
6241 ExprArg Base, ExprArg Idx) {
6242 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6243 static_cast<Expr*>(Idx.get()) };
6244 DeclarationName OpName =
6245 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6246
6247 // If either side is type-dependent, create an appropriate dependent
6248 // expression.
6249 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6250
John McCall58cc69d2010-01-27 01:50:18 +00006251 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006252 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006253 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006254 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006255 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006256 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006257
6258 Base.release();
6259 Idx.release();
6260 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6261 Args, 2,
6262 Context.DependentTy,
6263 RLoc));
6264 }
6265
6266 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006267 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006268
6269 // Subscript can only be overloaded as a member function.
6270
6271 // Add operator candidates that are member functions.
6272 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6273
6274 // Add builtin operator candidates.
6275 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6276
6277 // Perform overload resolution.
6278 OverloadCandidateSet::iterator Best;
6279 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6280 case OR_Success: {
6281 // We found a built-in operator or an overloaded operator.
6282 FunctionDecl *FnDecl = Best->Function;
6283
6284 if (FnDecl) {
6285 // We matched an overloaded operator. Build a call to that
6286 // operator.
6287
John McCalla0296f72010-03-19 07:35:19 +00006288 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +00006289
Sebastian Redladba46e2009-10-29 20:17:01 +00006290 // Convert the arguments.
6291 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006292 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006293 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006294 return ExprError();
6295
Anders Carlssona68e51e2010-01-29 18:37:50 +00006296 // Convert the arguments.
6297 OwningExprResult InputInit
6298 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6299 FnDecl->getParamDecl(0)),
6300 SourceLocation(),
6301 Owned(Args[1]));
6302 if (InputInit.isInvalid())
6303 return ExprError();
6304
6305 Args[1] = InputInit.takeAs<Expr>();
6306
Sebastian Redladba46e2009-10-29 20:17:01 +00006307 // Determine the result type
6308 QualType ResultTy
6309 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6310 ResultTy = ResultTy.getNonReferenceType();
6311
6312 // Build the actual expression node.
6313 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6314 LLoc);
6315 UsualUnaryConversions(FnExpr);
6316
6317 Base.release();
6318 Idx.release();
6319 ExprOwningPtr<CXXOperatorCallExpr>
6320 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6321 FnExpr, Args, 2,
6322 ResultTy, RLoc));
6323
6324 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6325 FnDecl))
6326 return ExprError();
6327
6328 return MaybeBindToTemporary(TheCall.release());
6329 } else {
6330 // We matched a built-in operator. Convert the arguments, then
6331 // break out so that we will build the appropriate built-in
6332 // operator node.
6333 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006334 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006335 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006336 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006337 return ExprError();
6338
6339 break;
6340 }
6341 }
6342
6343 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006344 if (CandidateSet.empty())
6345 Diag(LLoc, diag::err_ovl_no_oper)
6346 << Args[0]->getType() << /*subscript*/ 0
6347 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6348 else
6349 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6350 << Args[0]->getType()
6351 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006352 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006353 "[]", LLoc);
6354 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006355 }
6356
6357 case OR_Ambiguous:
6358 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6359 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006360 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006361 "[]", LLoc);
6362 return ExprError();
6363
6364 case OR_Deleted:
6365 Diag(LLoc, diag::err_ovl_deleted_oper)
6366 << Best->Function->isDeleted() << "[]"
6367 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006368 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006369 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006370 return ExprError();
6371 }
6372
6373 // We matched a built-in operator; build it.
6374 Base.release();
6375 Idx.release();
6376 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6377 Owned(Args[1]), RLoc);
6378}
6379
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006380/// BuildCallToMemberFunction - Build a call to a member
6381/// function. MemExpr is the expression that refers to the member
6382/// function (and includes the object parameter), Args/NumArgs are the
6383/// arguments to the function call (not including the object
6384/// parameter). The caller needs to validate that the member
6385/// expression refers to a member function or an overloaded member
6386/// function.
John McCall2d74de92009-12-01 22:10:20 +00006387Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006388Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6389 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006390 unsigned NumArgs, SourceLocation *CommaLocs,
6391 SourceLocation RParenLoc) {
6392 // Dig out the member expression. This holds both the object
6393 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006394 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6395
John McCall10eae182009-11-30 22:42:35 +00006396 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006397 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006398 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006399 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006400 if (isa<MemberExpr>(NakedMemExpr)) {
6401 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006402 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006403 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006404 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006405 } else {
6406 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006407 Qualifier = UnresExpr->getQualifier();
6408
John McCall6e9f8f62009-12-03 04:06:58 +00006409 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006410
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006411 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006412 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006413
John McCall2d74de92009-12-01 22:10:20 +00006414 // FIXME: avoid copy.
6415 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6416 if (UnresExpr->hasExplicitTemplateArgs()) {
6417 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6418 TemplateArgs = &TemplateArgsBuffer;
6419 }
6420
John McCall10eae182009-11-30 22:42:35 +00006421 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6422 E = UnresExpr->decls_end(); I != E; ++I) {
6423
John McCall6e9f8f62009-12-03 04:06:58 +00006424 NamedDecl *Func = *I;
6425 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6426 if (isa<UsingShadowDecl>(Func))
6427 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6428
John McCall10eae182009-11-30 22:42:35 +00006429 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006430 // If explicit template arguments were provided, we can't call a
6431 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006432 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006433 continue;
6434
John McCalla0296f72010-03-19 07:35:19 +00006435 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006436 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006437 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006438 } else {
John McCall10eae182009-11-30 22:42:35 +00006439 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006440 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006441 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006442 CandidateSet,
6443 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006444 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006445 }
Mike Stump11289f42009-09-09 15:08:12 +00006446
John McCall10eae182009-11-30 22:42:35 +00006447 DeclarationName DeclName = UnresExpr->getMemberName();
6448
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006449 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006450 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006451 case OR_Success:
6452 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006453 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006454 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006455 break;
6456
6457 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006458 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006459 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006460 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006461 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006462 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006463 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006464
6465 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006466 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006467 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006468 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006469 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006470 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006471
6472 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006473 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006474 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006475 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006476 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006477 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006478 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006479 }
6480
John McCall16df1e52010-03-30 21:47:33 +00006481 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006482
John McCall2d74de92009-12-01 22:10:20 +00006483 // If overload resolution picked a static member, build a
6484 // non-member call based on that function.
6485 if (Method->isStatic()) {
6486 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6487 Args, NumArgs, RParenLoc);
6488 }
6489
John McCall10eae182009-11-30 22:42:35 +00006490 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006491 }
6492
6493 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006494 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006495 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006496 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006497 Method->getResultType().getNonReferenceType(),
6498 RParenLoc));
6499
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006500 // Check for a valid return type.
6501 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6502 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006503 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006504
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006505 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006506 // We only need to do this if there was actually an overload; otherwise
6507 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006508 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006509 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006510 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6511 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006512 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006513 MemExpr->setBase(ObjectArg);
6514
6515 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00006516 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00006517 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006518 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006519 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006520
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006521 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006522 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006523
John McCall2d74de92009-12-01 22:10:20 +00006524 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006525}
6526
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006527/// BuildCallToObjectOfClassType - Build a call to an object of class
6528/// type (C++ [over.call.object]), which can end up invoking an
6529/// overloaded function call operator (@c operator()) or performing a
6530/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006531Sema::ExprResult
6532Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006533 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006534 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006535 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006536 SourceLocation RParenLoc) {
6537 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006538 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006539
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006540 // C++ [over.call.object]p1:
6541 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006542 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006543 // candidate functions includes at least the function call
6544 // operators of T. The function call operators of T are obtained by
6545 // ordinary lookup of the name operator() in the context of
6546 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006547 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006548 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006549
6550 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006551 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006552 << Object->getSourceRange()))
6553 return true;
6554
John McCall27b18f82009-11-17 02:14:36 +00006555 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6556 LookupQualifiedName(R, Record->getDecl());
6557 R.suppressDiagnostics();
6558
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006559 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006560 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006561 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006562 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006563 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006564 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006565
Douglas Gregorab7897a2008-11-19 22:57:39 +00006566 // C++ [over.call.object]p2:
6567 // In addition, for each conversion function declared in T of the
6568 // form
6569 //
6570 // operator conversion-type-id () cv-qualifier;
6571 //
6572 // where cv-qualifier is the same cv-qualification as, or a
6573 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006574 // denotes the type "pointer to function of (P1,...,Pn) returning
6575 // R", or the type "reference to pointer to function of
6576 // (P1,...,Pn) returning R", or the type "reference to function
6577 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006578 // is also considered as a candidate function. Similarly,
6579 // surrogate call functions are added to the set of candidate
6580 // functions for each conversion function declared in an
6581 // accessible base class provided the function is not hidden
6582 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006583 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006584 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006585 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006586 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006587 NamedDecl *D = *I;
6588 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6589 if (isa<UsingShadowDecl>(D))
6590 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6591
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006592 // Skip over templated conversion functions; they aren't
6593 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006594 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006595 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006596
John McCall6e9f8f62009-12-03 04:06:58 +00006597 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006598
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006599 // Strip the reference type (if any) and then the pointer type (if
6600 // any) to get down to what might be a function type.
6601 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6602 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6603 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006604
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006605 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006606 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006607 Object->getType(), Args, NumArgs,
6608 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006609 }
Mike Stump11289f42009-09-09 15:08:12 +00006610
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006611 // Perform overload resolution.
6612 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006613 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006614 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006615 // Overload resolution succeeded; we'll build the appropriate call
6616 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006617 break;
6618
6619 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006620 if (CandidateSet.empty())
6621 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6622 << Object->getType() << /*call*/ 1
6623 << Object->getSourceRange();
6624 else
6625 Diag(Object->getSourceRange().getBegin(),
6626 diag::err_ovl_no_viable_object_call)
6627 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006628 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006629 break;
6630
6631 case OR_Ambiguous:
6632 Diag(Object->getSourceRange().getBegin(),
6633 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006634 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006635 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006636 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006637
6638 case OR_Deleted:
6639 Diag(Object->getSourceRange().getBegin(),
6640 diag::err_ovl_deleted_object_call)
6641 << Best->Function->isDeleted()
6642 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006643 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006644 break;
Mike Stump11289f42009-09-09 15:08:12 +00006645 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006646
Douglas Gregorab7897a2008-11-19 22:57:39 +00006647 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006648 // We had an error; delete all of the subexpressions and return
6649 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006650 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006651 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006652 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006653 return true;
6654 }
6655
Douglas Gregorab7897a2008-11-19 22:57:39 +00006656 if (Best->Function == 0) {
6657 // Since there is no function declaration, this is one of the
6658 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006659 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006660 = cast<CXXConversionDecl>(
6661 Best->Conversions[0].UserDefined.ConversionFunction);
6662
John McCalla0296f72010-03-19 07:35:19 +00006663 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006664
Douglas Gregorab7897a2008-11-19 22:57:39 +00006665 // We selected one of the surrogate functions that converts the
6666 // object parameter to a function pointer. Perform the conversion
6667 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006668
6669 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006670 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006671 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6672 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006673
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006674 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006675 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006676 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006677 }
6678
John McCalla0296f72010-03-19 07:35:19 +00006679 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006680
Douglas Gregorab7897a2008-11-19 22:57:39 +00006681 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6682 // that calls this method, using Object for the implicit object
6683 // parameter and passing along the remaining arguments.
6684 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006685 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006686
6687 unsigned NumArgsInProto = Proto->getNumArgs();
6688 unsigned NumArgsToCheck = NumArgs;
6689
6690 // Build the full argument list for the method call (the
6691 // implicit object parameter is placed at the beginning of the
6692 // list).
6693 Expr **MethodArgs;
6694 if (NumArgs < NumArgsInProto) {
6695 NumArgsToCheck = NumArgsInProto;
6696 MethodArgs = new Expr*[NumArgsInProto + 1];
6697 } else {
6698 MethodArgs = new Expr*[NumArgs + 1];
6699 }
6700 MethodArgs[0] = Object;
6701 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6702 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006703
6704 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006705 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006706 UsualUnaryConversions(NewFn);
6707
6708 // Once we've built TheCall, all of the expressions are properly
6709 // owned.
6710 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006711 ExprOwningPtr<CXXOperatorCallExpr>
6712 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006713 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006714 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006715 delete [] MethodArgs;
6716
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006717 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6718 Method))
6719 return true;
6720
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006721 // We may have default arguments. If so, we need to allocate more
6722 // slots in the call for them.
6723 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006724 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006725 else if (NumArgs > NumArgsInProto)
6726 NumArgsToCheck = NumArgsInProto;
6727
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006728 bool IsError = false;
6729
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006730 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006731 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006732 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006733 TheCall->setArg(0, Object);
6734
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006735
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006736 // Check the argument types.
6737 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006738 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006739 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006740 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006741
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006742 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006743
6744 OwningExprResult InputInit
6745 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6746 Method->getParamDecl(i)),
6747 SourceLocation(), Owned(Arg));
6748
6749 IsError |= InputInit.isInvalid();
6750 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006751 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006752 OwningExprResult DefArg
6753 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6754 if (DefArg.isInvalid()) {
6755 IsError = true;
6756 break;
6757 }
6758
6759 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006760 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006761
6762 TheCall->setArg(i + 1, Arg);
6763 }
6764
6765 // If this is a variadic call, handle args passed through "...".
6766 if (Proto->isVariadic()) {
6767 // Promote the arguments (C99 6.5.2.2p7).
6768 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6769 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006770 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006771 TheCall->setArg(i + 1, Arg);
6772 }
6773 }
6774
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006775 if (IsError) return true;
6776
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006777 if (CheckFunctionCall(Method, TheCall.get()))
6778 return true;
6779
Douglas Gregore5e775b2010-04-13 15:50:39 +00006780 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006781}
6782
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006783/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006784/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006785/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006786Sema::OwningExprResult
6787Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6788 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006789 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006790
John McCallbc077cf2010-02-08 23:07:23 +00006791 SourceLocation Loc = Base->getExprLoc();
6792
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006793 // C++ [over.ref]p1:
6794 //
6795 // [...] An expression x->m is interpreted as (x.operator->())->m
6796 // for a class object x of type T if T::operator->() exists and if
6797 // the operator is selected as the best match function by the
6798 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006799 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006800 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006801 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006802
John McCallbc077cf2010-02-08 23:07:23 +00006803 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006804 PDiag(diag::err_typecheck_incomplete_tag)
6805 << Base->getSourceRange()))
6806 return ExprError();
6807
John McCall27b18f82009-11-17 02:14:36 +00006808 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6809 LookupQualifiedName(R, BaseRecord->getDecl());
6810 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006811
6812 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006813 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006814 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006815 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006816 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006817
6818 // Perform overload resolution.
6819 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006820 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006821 case OR_Success:
6822 // Overload resolution succeeded; we'll build the call below.
6823 break;
6824
6825 case OR_No_Viable_Function:
6826 if (CandidateSet.empty())
6827 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006828 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006829 else
6830 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006831 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006832 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006833 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006834
6835 case OR_Ambiguous:
6836 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006837 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006838 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006839 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006840
6841 case OR_Deleted:
6842 Diag(OpLoc, diag::err_ovl_deleted_oper)
6843 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006844 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006845 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006846 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006847 }
6848
John McCalla0296f72010-03-19 07:35:19 +00006849 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6850
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006851 // Convert the object parameter.
6852 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006853 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6854 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006855 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006856
6857 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006858 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006859
6860 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006861 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6862 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006863 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006864
6865 QualType ResultTy = Method->getResultType().getNonReferenceType();
6866 ExprOwningPtr<CXXOperatorCallExpr>
6867 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6868 &Base, 1, ResultTy, OpLoc));
6869
6870 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6871 Method))
6872 return ExprError();
6873 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006874}
6875
Douglas Gregorcd695e52008-11-10 20:40:00 +00006876/// FixOverloadedFunctionReference - E is an expression that refers to
6877/// a C++ overloaded function (possibly with some parentheses and
6878/// perhaps a '&' around it). We have resolved the overloaded function
6879/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006880/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00006881Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00006882 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006883 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006884 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6885 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006886 if (SubExpr == PE->getSubExpr())
6887 return PE->Retain();
6888
6889 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6890 }
6891
6892 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006893 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6894 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006895 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006896 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006897 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006898 if (SubExpr == ICE->getSubExpr())
6899 return ICE->Retain();
6900
6901 return new (Context) ImplicitCastExpr(ICE->getType(),
6902 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00006903 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006904 ICE->isLvalueCast());
6905 }
6906
6907 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006908 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006909 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6911 if (Method->isStatic()) {
6912 // Do nothing: static member functions aren't any different
6913 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006914 } else {
John McCalle66edc12009-11-24 19:00:30 +00006915 // Fix the sub expression, which really has to be an
6916 // UnresolvedLookupExpr holding an overloaded member function
6917 // or template.
John McCall16df1e52010-03-30 21:47:33 +00006918 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6919 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00006920 if (SubExpr == UnOp->getSubExpr())
6921 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006922
John McCalld14a8642009-11-21 08:51:07 +00006923 assert(isa<DeclRefExpr>(SubExpr)
6924 && "fixed to something other than a decl ref");
6925 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6926 && "fixed to a member ref with no nested name qualifier");
6927
6928 // We have taken the address of a pointer to member
6929 // function. Perform the computation here so that we get the
6930 // appropriate pointer to member type.
6931 QualType ClassType
6932 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6933 QualType MemPtrType
6934 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6935
6936 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6937 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006938 }
6939 }
John McCall16df1e52010-03-30 21:47:33 +00006940 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6941 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006942 if (SubExpr == UnOp->getSubExpr())
6943 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006944
Douglas Gregor51c538b2009-11-20 19:42:02 +00006945 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6946 Context.getPointerType(SubExpr->getType()),
6947 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006948 }
John McCalld14a8642009-11-21 08:51:07 +00006949
6950 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006951 // FIXME: avoid copy.
6952 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006953 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006954 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6955 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006956 }
6957
John McCalld14a8642009-11-21 08:51:07 +00006958 return DeclRefExpr::Create(Context,
6959 ULE->getQualifier(),
6960 ULE->getQualifierRange(),
6961 Fn,
6962 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006963 Fn->getType(),
6964 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006965 }
6966
John McCall10eae182009-11-30 22:42:35 +00006967 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006968 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006969 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6970 if (MemExpr->hasExplicitTemplateArgs()) {
6971 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6972 TemplateArgs = &TemplateArgsBuffer;
6973 }
John McCall6b51f282009-11-23 01:53:49 +00006974
John McCall2d74de92009-12-01 22:10:20 +00006975 Expr *Base;
6976
6977 // If we're filling in
6978 if (MemExpr->isImplicitAccess()) {
6979 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6980 return DeclRefExpr::Create(Context,
6981 MemExpr->getQualifier(),
6982 MemExpr->getQualifierRange(),
6983 Fn,
6984 MemExpr->getMemberLoc(),
6985 Fn->getType(),
6986 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006987 } else {
6988 SourceLocation Loc = MemExpr->getMemberLoc();
6989 if (MemExpr->getQualifier())
6990 Loc = MemExpr->getQualifierRange().getBegin();
6991 Base = new (Context) CXXThisExpr(Loc,
6992 MemExpr->getBaseType(),
6993 /*isImplicit=*/true);
6994 }
John McCall2d74de92009-12-01 22:10:20 +00006995 } else
6996 Base = MemExpr->getBase()->Retain();
6997
6998 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006999 MemExpr->isArrow(),
7000 MemExpr->getQualifier(),
7001 MemExpr->getQualifierRange(),
7002 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007003 Found,
John McCall6b51f282009-11-23 01:53:49 +00007004 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007005 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007006 Fn->getType());
7007 }
7008
Douglas Gregor51c538b2009-11-20 19:42:02 +00007009 assert(false && "Invalid reference to overloaded function");
7010 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007011}
7012
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007013Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007014 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007015 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007016 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007017}
7018
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007019} // end namespace clang