blob: 463f1899ed9bc7b07f87a0ee26bf60a23fffa2bd [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000229 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 break;
John McCall0d1da222010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000254 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261}
262
John McCall0d1da222010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
278
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000280// overload of the declarations in Old. This routine returns false if
281// New and Old cannot be overloaded, e.g., if New has the same
282// signature as some function in Old (C++ 1.3.10) or if the Old
283// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000284// it does return false, MatchedDecl will point to the decl that New
285// cannot be overloaded with. This decl may be a UsingShadowDecl on
286// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287//
288// Example: Given the following input:
289//
290// void f(int, float); // #1
291// void f(int, int); // #2
292// int f(int, int); // #3
293//
294// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296//
John McCall3d988d92009-12-02 08:47:38 +0000297// When we process #2, Old contains only the FunctionDecl for #1. By
298// comparing the parameter types, we see that #1 and #2 are overloaded
299// (since they have different signatures), so this routine returns
300// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301//
John McCall3d988d92009-12-02 08:47:38 +0000302// When we process #3, Old is an overload set containing #1 and #2. We
303// compare the signatures of #3 to #1 (they're overloaded, so we do
304// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
305// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000318 }
John McCall3d988d92009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000323 }
John McCall84d87672009-12-10 09:41:52 +0000324 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
325 // We can overload with these, which can show up when doing
326 // redeclaration checks for UsingDecls.
327 assert(Old.getLookupKind() == LookupUsingDeclName);
328 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
329 // Optimistically assume that an unresolved using decl will
330 // overload; if it doesn't, we'll have to diagnose during
331 // template instantiation.
332 } else {
John McCall1f82f242009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000338 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339 }
John McCall1f82f242009-11-18 22:49:29 +0000340
John McCalldaa3d6b2009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000342}
343
344bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
345 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
346 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
347
348 // C++ [temp.fct]p2:
349 // A function template can be overloaded with other function templates
350 // and with normal (non-template) functions.
351 if ((OldTemplate == 0) != (NewTemplate == 0))
352 return true;
353
354 // Is the function New an overload of the function Old?
355 QualType OldQType = Context.getCanonicalType(Old->getType());
356 QualType NewQType = Context.getCanonicalType(New->getType());
357
358 // Compare the signatures (C++ 1.3.10) of the two functions to
359 // determine whether they are overloads. If we find any mismatch
360 // in the signature, they are overloads.
361
362 // If either of these functions is a K&R-style function (no
363 // prototype), then we consider them to have matching signatures.
364 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
365 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
366 return false;
367
368 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
369 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
370
371 // The signature of a function includes the types of its
372 // parameters (C++ 1.3.10), which includes the presence or absence
373 // of the ellipsis; see C++ DR 357).
374 if (OldQType != NewQType &&
375 (OldType->getNumArgs() != NewType->getNumArgs() ||
376 OldType->isVariadic() != NewType->isVariadic() ||
377 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
378 NewType->arg_type_begin())))
379 return true;
380
381 // C++ [temp.over.link]p4:
382 // The signature of a function template consists of its function
383 // signature, its return type and its template parameter list. The names
384 // of the template parameters are significant only for establishing the
385 // relationship between the template parameters and the rest of the
386 // signature.
387 //
388 // We check the return type and template parameter lists for function
389 // templates first; the remaining checks follow.
390 if (NewTemplate &&
391 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
392 OldTemplate->getTemplateParameters(),
393 false, TPL_TemplateMatch) ||
394 OldType->getResultType() != NewType->getResultType()))
395 return true;
396
397 // If the function is a class member, its signature includes the
398 // cv-qualifiers (if any) on the function itself.
399 //
400 // As part of this, also check whether one of the member functions
401 // is static, in which case they are not overloads (C++
402 // 13.1p2). While not part of the definition of the signature,
403 // this check is important to determine whether these functions
404 // can be overloaded.
405 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
406 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
407 if (OldMethod && NewMethod &&
408 !OldMethod->isStatic() && !NewMethod->isStatic() &&
409 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
410 return true;
411
412 // The signatures match; this is not an overload.
413 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000414}
415
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000416/// TryImplicitConversion - Attempt to perform an implicit conversion
417/// from the given expression (Expr) to the given type (ToType). This
418/// function returns an implicit conversion sequence that can be used
419/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000420///
421/// void f(float f);
422/// void g(int i) { f(i); }
423///
424/// this routine would produce an implicit conversion sequence to
425/// describe the initialization of f from i, which will be a standard
426/// conversion sequence containing an lvalue-to-rvalue conversion (C++
427/// 4.1) followed by a floating-integral conversion (C++ 4.9).
428//
429/// Note that this routine only determines how the conversion can be
430/// performed; it does not actually perform the conversion. As such,
431/// it will not produce any diagnostics if no conversion is available,
432/// but will instead return an implicit conversion sequence of kind
433/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000439ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000440Sema::TryImplicitConversion(Expr* From, QualType ToType,
441 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000442 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000443 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000444 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000445 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000446 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000447 return ICS;
448 }
449
450 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000451 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000452 return ICS;
453 }
454
Douglas Gregor5ab11652010-04-17 22:01:05 +0000455 if (SuppressUserConversions) {
456 // C++ [over.ics.user]p4:
457 // A conversion of an expression of class type to the same class
458 // type is given Exact Match rank, and a conversion of an
459 // expression of class type to a base class of that type is
460 // given Conversion rank, in spite of the fact that a copy/move
461 // constructor (i.e., a user-defined conversion function) is
462 // called for those cases.
463 QualType FromType = From->getType();
464 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
465 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
466 IsDerivedFrom(FromType, ToType))) {
467 // We're not in the case above, so there is no conversion that
468 // we can perform.
469 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
470 return ICS;
471 }
472
473 ICS.setStandard();
474 ICS.Standard.setAsIdentityConversion();
475 ICS.Standard.setFromType(FromType);
476 ICS.Standard.setAllToTypes(ToType);
477
478 // We don't actually check at this point whether there is a valid
479 // copy/move constructor, since overloading just assumes that it
480 // exists. When we actually perform initialization, we'll find the
481 // appropriate constructor to copy the returned object, if needed.
482 ICS.Standard.CopyConstructor = 0;
483
484 // Determine whether this is considered a derived-to-base conversion.
485 if (!Context.hasSameUnqualifiedType(FromType, ToType))
486 ICS.Standard.Second = ICK_Derived_To_Base;
487
488 return ICS;
489 }
490
491 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000492 OverloadCandidateSet Conversions(From->getExprLoc());
493 OverloadingResult UserDefResult
494 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000495 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000496
497 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000498 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000499 // C++ [over.ics.user]p4:
500 // A conversion of an expression of class type to the same class
501 // type is given Exact Match rank, and a conversion of an
502 // expression of class type to a base class of that type is
503 // given Conversion rank, in spite of the fact that a copy
504 // constructor (i.e., a user-defined conversion function) is
505 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000506 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000507 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000508 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000509 = Context.getCanonicalType(From->getType().getUnqualifiedType());
510 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000511 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000512 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000513 // Turn this into a "standard" conversion sequence, so that it
514 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000515 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000516 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000517 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000518 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000519 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000520 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000521 ICS.Standard.Second = ICK_Derived_To_Base;
522 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000523 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000524
525 // C++ [over.best.ics]p4:
526 // However, when considering the argument of a user-defined
527 // conversion function that is a candidate by 13.3.1.3 when
528 // invoked for the copying of the temporary in the second step
529 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
530 // 13.3.1.6 in all cases, only standard conversion sequences and
531 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000532 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000533 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000534 }
John McCalle8c8cd22010-01-13 22:30:33 +0000535 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000536 ICS.setAmbiguous();
537 ICS.Ambiguous.setFromType(From->getType());
538 ICS.Ambiguous.setToType(ToType);
539 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
540 Cand != Conversions.end(); ++Cand)
541 if (Cand->Viable)
542 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000543 } else {
John McCall65eb8792010-02-25 01:37:24 +0000544 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000545 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000546
547 return ICS;
548}
549
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000550/// PerformImplicitConversion - Perform an implicit conversion of the
551/// expression From to the type ToType. Returns true if there was an
552/// error, false otherwise. The expression From is replaced with the
553/// converted expression. Flavor is the kind of conversion we're
554/// performing, used in the error message. If @p AllowExplicit,
555/// explicit user-defined conversions are permitted.
556bool
557Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
558 AssignmentAction Action, bool AllowExplicit) {
559 ImplicitConversionSequence ICS;
560 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
561}
562
563bool
564Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
565 AssignmentAction Action, bool AllowExplicit,
566 ImplicitConversionSequence& ICS) {
567 ICS = TryImplicitConversion(From, ToType,
568 /*SuppressUserConversions=*/false,
569 AllowExplicit,
570 /*InOverloadResolution=*/false);
571 return PerformImplicitConversion(From, ToType, ICS, Action);
572}
573
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000574/// \brief Determine whether the conversion from FromType to ToType is a valid
575/// conversion that strips "noreturn" off the nested function type.
576static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
577 QualType ToType, QualType &ResultTy) {
578 if (Context.hasSameUnqualifiedType(FromType, ToType))
579 return false;
580
581 // Strip the noreturn off the type we're converting from; noreturn can
582 // safely be removed.
583 FromType = Context.getNoReturnType(FromType, false);
584 if (!Context.hasSameUnqualifiedType(FromType, ToType))
585 return false;
586
587 ResultTy = FromType;
588 return true;
589}
590
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000591/// IsStandardConversion - Determines whether there is a standard
592/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
593/// expression From to the type ToType. Standard conversion sequences
594/// only consider non-class types; for conversions that involve class
595/// types, use TryImplicitConversion. If a conversion exists, SCS will
596/// contain the standard conversion sequence required to perform this
597/// conversion and this routine will return true. Otherwise, this
598/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000599bool
600Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000601 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000602 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603 QualType FromType = From->getType();
604
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000605 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000606 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000607 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000608 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000609 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000610 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000611
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000612 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000613 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000614 if (FromType->isRecordType() || ToType->isRecordType()) {
615 if (getLangOptions().CPlusPlus)
616 return false;
617
Mike Stump11289f42009-09-09 15:08:12 +0000618 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000619 }
620
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000621 // The first conversion can be an lvalue-to-rvalue conversion,
622 // array-to-pointer conversion, or function-to-pointer conversion
623 // (C++ 4p1).
624
John McCall16df1e52010-03-30 21:47:33 +0000625 DeclAccessPair AccessPair;
626
Mike Stump11289f42009-09-09 15:08:12 +0000627 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000628 // An lvalue (3.10) of a non-function, non-array type T can be
629 // converted to an rvalue.
630 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000631 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000632 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000633 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000634 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000635
636 // If T is a non-class type, the type of the rvalue is the
637 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000638 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
639 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000640 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000641 } else if (FromType->isArrayType()) {
642 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000643 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000644
645 // An lvalue or rvalue of type "array of N T" or "array of unknown
646 // bound of T" can be converted to an rvalue of type "pointer to
647 // T" (C++ 4.2p1).
648 FromType = Context.getArrayDecayedType(FromType);
649
650 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
651 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000652 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653
654 // For the purpose of ranking in overload resolution
655 // (13.3.3.1.1), this conversion is considered an
656 // array-to-pointer conversion followed by a qualification
657 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000658 SCS.Second = ICK_Identity;
659 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000660 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000662 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000663 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
664 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000665 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000666
667 // An lvalue of function type T can be converted to an rvalue of
668 // type "pointer to T." The result is a pointer to the
669 // function. (C++ 4.3p1).
670 FromType = Context.getPointerType(FromType);
Douglas Gregor064fdb22010-04-14 23:11:21 +0000671 } else if (From->getType() == Context.OverloadTy) {
672 if (FunctionDecl *Fn
673 = ResolveAddressOfOverloadedFunction(From, ToType, false,
674 AccessPair)) {
675 // Address of overloaded function (C++ [over.over]).
676 SCS.First = ICK_Function_To_Pointer;
Douglas Gregorcd695e52008-11-10 20:40:00 +0000677
Douglas Gregor064fdb22010-04-14 23:11:21 +0000678 // We were able to resolve the address of the overloaded function,
679 // so we can convert to the type of that function.
680 FromType = Fn->getType();
681 if (ToType->isLValueReferenceType())
682 FromType = Context.getLValueReferenceType(FromType);
683 else if (ToType->isRValueReferenceType())
684 FromType = Context.getRValueReferenceType(FromType);
685 else if (ToType->isMemberPointerType()) {
686 // Resolve address only succeeds if both sides are member pointers,
687 // but it doesn't have to be the same class. See DR 247.
688 // Note that this means that the type of &Derived::fn can be
689 // Ret (Base::*)(Args) if the fn overload actually found is from the
690 // base class, even if it was brought into the derived class via a
691 // using declaration. The standard isn't clear on this issue at all.
692 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
693 FromType = Context.getMemberPointerType(FromType,
694 Context.getTypeDeclType(M->getParent()).getTypePtr());
695 } else {
696 FromType = Context.getPointerType(FromType);
697 }
698 } else {
699 return false;
700 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000701 } else {
702 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000703 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000704 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000705 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000706
707 // The second conversion can be an integral promotion, floating
708 // point promotion, integral conversion, floating point conversion,
709 // floating-integral conversion, pointer conversion,
710 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000711 // For overloading in C, this can also be a "compatible-type"
712 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000713 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000714 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000715 // The unqualified versions of the types are the same: there's no
716 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000717 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000718 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000719 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000720 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000721 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000722 } else if (IsFloatingPointPromotion(FromType, ToType)) {
723 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000724 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000726 } else if (IsComplexPromotion(FromType, ToType)) {
727 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000728 SCS.Second = ICK_Complex_Promotion;
729 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000730 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000731 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000732 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000733 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000734 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000735 } else if (FromType->isComplexType() && ToType->isComplexType()) {
736 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000737 SCS.Second = ICK_Complex_Conversion;
738 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000739 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
740 (ToType->isComplexType() && FromType->isArithmeticType())) {
741 // Complex-real conversions (C99 6.3.1.7)
742 SCS.Second = ICK_Complex_Real;
743 FromType = ToType.getUnqualifiedType();
744 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
745 // Floating point conversions (C++ 4.8).
746 SCS.Second = ICK_Floating_Conversion;
747 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000748 } else if ((FromType->isFloatingType() &&
749 ToType->isIntegralType() && (!ToType->isBooleanType() &&
750 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000751 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000752 ToType->isFloatingType())) {
753 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000754 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000755 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000756 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
757 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000758 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000759 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000760 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000761 } else if (IsMemberPointerConversion(From, FromType, ToType,
762 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000763 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000764 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000765 } else if (ToType->isBooleanType() &&
766 (FromType->isArithmeticType() ||
767 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000768 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000769 FromType->isBlockPointerType() ||
770 FromType->isMemberPointerType() ||
771 FromType->isNullPtrType())) {
772 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000773 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000774 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000775 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000776 Context.typesAreCompatible(ToType, FromType)) {
777 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000778 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000779 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
780 // Treat a conversion that strips "noreturn" as an identity conversion.
781 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000782 } else {
783 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000784 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000785 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000786 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000788 QualType CanonFrom;
789 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000790 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000791 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000792 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000793 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000794 CanonFrom = Context.getCanonicalType(FromType);
795 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000796 } else {
797 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000798 SCS.Third = ICK_Identity;
799
Mike Stump11289f42009-09-09 15:08:12 +0000800 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000801 // [...] Any difference in top-level cv-qualification is
802 // subsumed by the initialization itself and does not constitute
803 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000804 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000805 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000806 if (CanonFrom.getLocalUnqualifiedType()
807 == CanonTo.getLocalUnqualifiedType() &&
808 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000809 FromType = ToType;
810 CanonFrom = CanonTo;
811 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000812 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000813 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000814
815 // If we have not converted the argument type to the parameter type,
816 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000817 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000818 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000819
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000820 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000821}
822
823/// IsIntegralPromotion - Determines whether the conversion from the
824/// expression From (whose potentially-adjusted type is FromType) to
825/// ToType is an integral promotion (C++ 4.5). If so, returns true and
826/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000827bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000828 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000829 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000830 if (!To) {
831 return false;
832 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000833
834 // An rvalue of type char, signed char, unsigned char, short int, or
835 // unsigned short int can be converted to an rvalue of type int if
836 // int can represent all the values of the source type; otherwise,
837 // the source rvalue can be converted to an rvalue of type unsigned
838 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000839 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
840 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000841 if (// We can promote any signed, promotable integer type to an int
842 (FromType->isSignedIntegerType() ||
843 // We can promote any unsigned integer type whose size is
844 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000845 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000846 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000848 }
849
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000850 return To->getKind() == BuiltinType::UInt;
851 }
852
853 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
854 // can be converted to an rvalue of the first of the following types
855 // that can represent all the values of its underlying type: int,
856 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000857
858 // We pre-calculate the promotion type for enum types.
859 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
860 if (ToType->isIntegerType())
861 return Context.hasSameUnqualifiedType(ToType,
862 FromEnumType->getDecl()->getPromotionType());
863
864 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000865 // Determine whether the type we're converting from is signed or
866 // unsigned.
867 bool FromIsSigned;
868 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000869
870 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
871 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872
873 // The types we'll try to promote to, in the appropriate
874 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000875 QualType PromoteTypes[6] = {
876 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000877 Context.LongTy, Context.UnsignedLongTy ,
878 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000879 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000880 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000881 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
882 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000883 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000884 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
885 // We found the type that we can promote to. If this is the
886 // type we wanted, we have a promotion. Otherwise, no
887 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000888 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889 }
890 }
891 }
892
893 // An rvalue for an integral bit-field (9.6) can be converted to an
894 // rvalue of type int if int can represent all the values of the
895 // bit-field; otherwise, it can be converted to unsigned int if
896 // unsigned int can represent all the values of the bit-field. If
897 // the bit-field is larger yet, no integral promotion applies to
898 // it. If the bit-field has an enumerated type, it is treated as any
899 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000900 // FIXME: We should delay checking of bit-fields until we actually perform the
901 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000902 using llvm::APSInt;
903 if (From)
904 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000905 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000906 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
907 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
908 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
909 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000910
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000911 // Are we promoting to an int from a bitfield that fits in an int?
912 if (BitWidth < ToSize ||
913 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
914 return To->getKind() == BuiltinType::Int;
915 }
Mike Stump11289f42009-09-09 15:08:12 +0000916
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000917 // Are we promoting to an unsigned int from an unsigned bitfield
918 // that fits into an unsigned int?
919 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
920 return To->getKind() == BuiltinType::UInt;
921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000923 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000924 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000925 }
Mike Stump11289f42009-09-09 15:08:12 +0000926
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000927 // An rvalue of type bool can be converted to an rvalue of type int,
928 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000929 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000930 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000931 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000932
933 return false;
934}
935
936/// IsFloatingPointPromotion - Determines whether the conversion from
937/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
938/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000939bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000940 /// An rvalue of type float can be converted to an rvalue of type
941 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000942 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
943 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000944 if (FromBuiltin->getKind() == BuiltinType::Float &&
945 ToBuiltin->getKind() == BuiltinType::Double)
946 return true;
947
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000948 // C99 6.3.1.5p1:
949 // When a float is promoted to double or long double, or a
950 // double is promoted to long double [...].
951 if (!getLangOptions().CPlusPlus &&
952 (FromBuiltin->getKind() == BuiltinType::Float ||
953 FromBuiltin->getKind() == BuiltinType::Double) &&
954 (ToBuiltin->getKind() == BuiltinType::LongDouble))
955 return true;
956 }
957
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000958 return false;
959}
960
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000961/// \brief Determine if a conversion is a complex promotion.
962///
963/// A complex promotion is defined as a complex -> complex conversion
964/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000965/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000966bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000967 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000968 if (!FromComplex)
969 return false;
970
John McCall9dd450b2009-09-21 23:43:11 +0000971 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000972 if (!ToComplex)
973 return false;
974
975 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000976 ToComplex->getElementType()) ||
977 IsIntegralPromotion(0, FromComplex->getElementType(),
978 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000979}
980
Douglas Gregor237f96c2008-11-26 23:31:11 +0000981/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
982/// the pointer type FromPtr to a pointer to type ToPointee, with the
983/// same type qualifiers as FromPtr has on its pointee type. ToType,
984/// if non-empty, will be a pointer to ToType that may or may not have
985/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000986static QualType
987BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000988 QualType ToPointee, QualType ToType,
989 ASTContext &Context) {
990 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
991 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000992 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000993
994 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000995 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000996 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000997 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000998 return ToType;
999
1000 // Build a pointer to ToPointee. It has the right qualifiers
1001 // already.
1002 return Context.getPointerType(ToPointee);
1003 }
1004
1005 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001006 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001007 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1008 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001009}
1010
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001011/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1012/// the FromType, which is an objective-c pointer, to ToType, which may or may
1013/// not have the right set of qualifiers.
1014static QualType
1015BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1016 QualType ToType,
1017 ASTContext &Context) {
1018 QualType CanonFromType = Context.getCanonicalType(FromType);
1019 QualType CanonToType = Context.getCanonicalType(ToType);
1020 Qualifiers Quals = CanonFromType.getQualifiers();
1021
1022 // Exact qualifier match -> return the pointer type we're converting to.
1023 if (CanonToType.getLocalQualifiers() == Quals)
1024 return ToType;
1025
1026 // Just build a canonical type that has the right qualifiers.
1027 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1028}
1029
Mike Stump11289f42009-09-09 15:08:12 +00001030static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001031 bool InOverloadResolution,
1032 ASTContext &Context) {
1033 // Handle value-dependent integral null pointer constants correctly.
1034 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1035 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1036 Expr->getType()->isIntegralType())
1037 return !InOverloadResolution;
1038
Douglas Gregor56751b52009-09-25 04:25:58 +00001039 return Expr->isNullPointerConstant(Context,
1040 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1041 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001042}
Mike Stump11289f42009-09-09 15:08:12 +00001043
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001044/// IsPointerConversion - Determines whether the conversion of the
1045/// expression From, which has the (possibly adjusted) type FromType,
1046/// can be converted to the type ToType via a pointer conversion (C++
1047/// 4.10). If so, returns true and places the converted type (that
1048/// might differ from ToType in its cv-qualifiers at some level) into
1049/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001050///
Douglas Gregora29dc052008-11-27 01:19:21 +00001051/// This routine also supports conversions to and from block pointers
1052/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1053/// pointers to interfaces. FIXME: Once we've determined the
1054/// appropriate overloading rules for Objective-C, we may want to
1055/// split the Objective-C checks into a different routine; however,
1056/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001057/// conversions, so for now they live here. IncompatibleObjC will be
1058/// set if the conversion is an allowed Objective-C conversion that
1059/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001060bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001061 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001062 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001063 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001064 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001065 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1066 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001067
Mike Stump11289f42009-09-09 15:08:12 +00001068 // Conversion from a null pointer constant to any Objective-C pointer type.
1069 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001070 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001071 ConvertedType = ToType;
1072 return true;
1073 }
1074
Douglas Gregor231d1c62008-11-27 00:15:41 +00001075 // Blocks: Block pointers can be converted to void*.
1076 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001077 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001078 ConvertedType = ToType;
1079 return true;
1080 }
1081 // Blocks: A null pointer constant can be converted to a block
1082 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001083 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001084 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001085 ConvertedType = ToType;
1086 return true;
1087 }
1088
Sebastian Redl576fd422009-05-10 18:38:11 +00001089 // If the left-hand-side is nullptr_t, the right side can be a null
1090 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001091 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001092 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001093 ConvertedType = ToType;
1094 return true;
1095 }
1096
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001097 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001098 if (!ToTypePtr)
1099 return false;
1100
1101 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001102 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103 ConvertedType = ToType;
1104 return true;
1105 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001106
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001107 // Beyond this point, both types need to be pointers
1108 // , including objective-c pointers.
1109 QualType ToPointeeType = ToTypePtr->getPointeeType();
1110 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1111 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1112 ToType, Context);
1113 return true;
1114
1115 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001116 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001117 if (!FromTypePtr)
1118 return false;
1119
1120 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001121
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122 // An rvalue of type "pointer to cv T," where T is an object type,
1123 // can be converted to an rvalue of type "pointer to cv void" (C++
1124 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001125 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001126 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001127 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001128 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 return true;
1130 }
1131
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001132 // When we're overloading in C, we allow a special kind of pointer
1133 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001134 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001135 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001136 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001137 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001138 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001139 return true;
1140 }
1141
Douglas Gregor5c407d92008-10-23 00:40:37 +00001142 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001143 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001144 // An rvalue of type "pointer to cv D," where D is a class type,
1145 // can be converted to an rvalue of type "pointer to cv B," where
1146 // B is a base class (clause 10) of D. If B is an inaccessible
1147 // (clause 11) or ambiguous (10.2) base class of D, a program that
1148 // necessitates this conversion is ill-formed. The result of the
1149 // conversion is a pointer to the base class sub-object of the
1150 // derived class object. The null pointer value is converted to
1151 // the null pointer value of the destination type.
1152 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001153 // Note that we do not check for ambiguity or inaccessibility
1154 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001155 if (getLangOptions().CPlusPlus &&
1156 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001157 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001158 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001159 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001160 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001161 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001162 ToType, Context);
1163 return true;
1164 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001165
Douglas Gregora119f102008-12-19 19:13:09 +00001166 return false;
1167}
1168
1169/// isObjCPointerConversion - Determines whether this is an
1170/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1171/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001172bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001173 QualType& ConvertedType,
1174 bool &IncompatibleObjC) {
1175 if (!getLangOptions().ObjC1)
1176 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001177
Steve Naroff7cae42b2009-07-10 23:34:53 +00001178 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001179 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001180 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001181 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001182
Steve Naroff7cae42b2009-07-10 23:34:53 +00001183 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001184 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001185 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001186 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001187 ConvertedType = ToType;
1188 return true;
1189 }
1190 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001191 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001192 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001193 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001194 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001195 ConvertedType = ToType;
1196 return true;
1197 }
1198 // Objective C++: We're able to convert from a pointer to an
1199 // interface to a pointer to a different interface.
1200 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001201 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1202 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1203 if (getLangOptions().CPlusPlus && LHS && RHS &&
1204 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1205 FromObjCPtr->getPointeeType()))
1206 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001207 ConvertedType = ToType;
1208 return true;
1209 }
1210
1211 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1212 // Okay: this is some kind of implicit downcast of Objective-C
1213 // interfaces, which is permitted. However, we're going to
1214 // complain about it.
1215 IncompatibleObjC = true;
1216 ConvertedType = FromType;
1217 return true;
1218 }
Mike Stump11289f42009-09-09 15:08:12 +00001219 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001220 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001221 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001222 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001223 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001224 else if (const BlockPointerType *ToBlockPtr =
1225 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001226 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001227 // to a block pointer type.
1228 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1229 ConvertedType = ToType;
1230 return true;
1231 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001232 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001233 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001234 else if (FromType->getAs<BlockPointerType>() &&
1235 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1236 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001237 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001238 ConvertedType = ToType;
1239 return true;
1240 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001241 else
Douglas Gregora119f102008-12-19 19:13:09 +00001242 return false;
1243
Douglas Gregor033f56d2008-12-23 00:53:59 +00001244 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001245 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001246 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001247 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001248 FromPointeeType = FromBlockPtr->getPointeeType();
1249 else
Douglas Gregora119f102008-12-19 19:13:09 +00001250 return false;
1251
Douglas Gregora119f102008-12-19 19:13:09 +00001252 // If we have pointers to pointers, recursively check whether this
1253 // is an Objective-C conversion.
1254 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1255 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1256 IncompatibleObjC)) {
1257 // We always complain about this conversion.
1258 IncompatibleObjC = true;
1259 ConvertedType = ToType;
1260 return true;
1261 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001262 // Allow conversion of pointee being objective-c pointer to another one;
1263 // as in I* to id.
1264 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1265 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1266 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1267 IncompatibleObjC)) {
1268 ConvertedType = ToType;
1269 return true;
1270 }
1271
Douglas Gregor033f56d2008-12-23 00:53:59 +00001272 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001273 // differences in the argument and result types are in Objective-C
1274 // pointer conversions. If so, we permit the conversion (but
1275 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001276 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001277 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001278 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001279 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001280 if (FromFunctionType && ToFunctionType) {
1281 // If the function types are exactly the same, this isn't an
1282 // Objective-C pointer conversion.
1283 if (Context.getCanonicalType(FromPointeeType)
1284 == Context.getCanonicalType(ToPointeeType))
1285 return false;
1286
1287 // Perform the quick checks that will tell us whether these
1288 // function types are obviously different.
1289 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1290 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1291 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1292 return false;
1293
1294 bool HasObjCConversion = false;
1295 if (Context.getCanonicalType(FromFunctionType->getResultType())
1296 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1297 // Okay, the types match exactly. Nothing to do.
1298 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1299 ToFunctionType->getResultType(),
1300 ConvertedType, IncompatibleObjC)) {
1301 // Okay, we have an Objective-C pointer conversion.
1302 HasObjCConversion = true;
1303 } else {
1304 // Function types are too different. Abort.
1305 return false;
1306 }
Mike Stump11289f42009-09-09 15:08:12 +00001307
Douglas Gregora119f102008-12-19 19:13:09 +00001308 // Check argument types.
1309 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1310 ArgIdx != NumArgs; ++ArgIdx) {
1311 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1312 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1313 if (Context.getCanonicalType(FromArgType)
1314 == Context.getCanonicalType(ToArgType)) {
1315 // Okay, the types match exactly. Nothing to do.
1316 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1317 ConvertedType, IncompatibleObjC)) {
1318 // Okay, we have an Objective-C pointer conversion.
1319 HasObjCConversion = true;
1320 } else {
1321 // Argument types are too different. Abort.
1322 return false;
1323 }
1324 }
1325
1326 if (HasObjCConversion) {
1327 // We had an Objective-C conversion. Allow this pointer
1328 // conversion, but complain about it.
1329 ConvertedType = ToType;
1330 IncompatibleObjC = true;
1331 return true;
1332 }
1333 }
1334
Sebastian Redl72b597d2009-01-25 19:43:20 +00001335 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001336}
1337
Douglas Gregor39c16d42008-10-24 04:54:22 +00001338/// CheckPointerConversion - Check the pointer conversion from the
1339/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001340/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001341/// conversions for which IsPointerConversion has already returned
1342/// true. It returns true and produces a diagnostic if there was an
1343/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001344bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001345 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001346 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001347 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001348 QualType FromType = From->getType();
1349
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001350 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1351 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001352 QualType FromPointeeType = FromPtrType->getPointeeType(),
1353 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001354
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001355 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1356 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001357 // We must have a derived-to-base conversion. Check an
1358 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001359 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1360 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001361 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001362 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001363 return true;
1364
1365 // The conversion was successful.
1366 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001367 }
1368 }
Mike Stump11289f42009-09-09 15:08:12 +00001369 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001370 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001371 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001372 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001373 // Objective-C++ conversions are always okay.
1374 // FIXME: We should have a different class of conversions for the
1375 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001376 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001377 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001378
Steve Naroff7cae42b2009-07-10 23:34:53 +00001379 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001380 return false;
1381}
1382
Sebastian Redl72b597d2009-01-25 19:43:20 +00001383/// IsMemberPointerConversion - Determines whether the conversion of the
1384/// expression From, which has the (possibly adjusted) type FromType, can be
1385/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1386/// If so, returns true and places the converted type (that might differ from
1387/// ToType in its cv-qualifiers at some level) into ConvertedType.
1388bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001389 QualType ToType,
1390 bool InOverloadResolution,
1391 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001392 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001393 if (!ToTypePtr)
1394 return false;
1395
1396 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001397 if (From->isNullPointerConstant(Context,
1398 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1399 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001400 ConvertedType = ToType;
1401 return true;
1402 }
1403
1404 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001405 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001406 if (!FromTypePtr)
1407 return false;
1408
1409 // A pointer to member of B can be converted to a pointer to member of D,
1410 // where D is derived from B (C++ 4.11p2).
1411 QualType FromClass(FromTypePtr->getClass(), 0);
1412 QualType ToClass(ToTypePtr->getClass(), 0);
1413 // FIXME: What happens when these are dependent? Is this function even called?
1414
1415 if (IsDerivedFrom(ToClass, FromClass)) {
1416 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1417 ToClass.getTypePtr());
1418 return true;
1419 }
1420
1421 return false;
1422}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001423
Sebastian Redl72b597d2009-01-25 19:43:20 +00001424/// CheckMemberPointerConversion - Check the member pointer conversion from the
1425/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001426/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001427/// for which IsMemberPointerConversion has already returned true. It returns
1428/// true and produces a diagnostic if there was an error, or returns false
1429/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001430bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001431 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001432 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001433 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001434 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001435 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001436 if (!FromPtrType) {
1437 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001438 assert(From->isNullPointerConstant(Context,
1439 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001440 "Expr must be null pointer constant!");
1441 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001442 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001443 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001444
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001445 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001446 assert(ToPtrType && "No member pointer cast has a target type "
1447 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001448
Sebastian Redled8f2002009-01-28 18:33:18 +00001449 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1450 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001451
Sebastian Redled8f2002009-01-28 18:33:18 +00001452 // FIXME: What about dependent types?
1453 assert(FromClass->isRecordType() && "Pointer into non-class.");
1454 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001455
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001456 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001457 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001458 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1459 assert(DerivationOkay &&
1460 "Should not have been called if derivation isn't OK.");
1461 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001462
Sebastian Redled8f2002009-01-28 18:33:18 +00001463 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1464 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001465 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1466 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1467 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1468 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001469 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001470
Douglas Gregor89ee6822009-02-28 01:32:25 +00001471 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001472 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1473 << FromClass << ToClass << QualType(VBase, 0)
1474 << From->getSourceRange();
1475 return true;
1476 }
1477
John McCall5b0829a2010-02-10 09:31:12 +00001478 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001479 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1480 Paths.front(),
1481 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001482
Anders Carlssond7923c62009-08-22 23:33:40 +00001483 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001484 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001485 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001486 return false;
1487}
1488
Douglas Gregor9a657932008-10-21 23:43:52 +00001489/// IsQualificationConversion - Determines whether the conversion from
1490/// an rvalue of type FromType to ToType is a qualification conversion
1491/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001492bool
1493Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001494 FromType = Context.getCanonicalType(FromType);
1495 ToType = Context.getCanonicalType(ToType);
1496
1497 // If FromType and ToType are the same type, this is not a
1498 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001499 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001500 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001501
Douglas Gregor9a657932008-10-21 23:43:52 +00001502 // (C++ 4.4p4):
1503 // A conversion can add cv-qualifiers at levels other than the first
1504 // in multi-level pointers, subject to the following rules: [...]
1505 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001506 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001507 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001508 // Within each iteration of the loop, we check the qualifiers to
1509 // determine if this still looks like a qualification
1510 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001511 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001512 // until there are no more pointers or pointers-to-members left to
1513 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001514 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001515
1516 // -- for every j > 0, if const is in cv 1,j then const is in cv
1517 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001518 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001519 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001520
Douglas Gregor9a657932008-10-21 23:43:52 +00001521 // -- if the cv 1,j and cv 2,j are different, then const is in
1522 // every cv for 0 < k < j.
1523 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001524 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001525 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001526
Douglas Gregor9a657932008-10-21 23:43:52 +00001527 // Keep track of whether all prior cv-qualifiers in the "to" type
1528 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001529 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001530 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001531 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001532
1533 // We are left with FromType and ToType being the pointee types
1534 // after unwrapping the original FromType and ToType the same number
1535 // of types. If we unwrapped any pointers, and if FromType and
1536 // ToType have the same unqualified type (since we checked
1537 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001538 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001539}
1540
Douglas Gregor576e98c2009-01-30 23:27:23 +00001541/// Determines whether there is a user-defined conversion sequence
1542/// (C++ [over.ics.user]) that converts expression From to the type
1543/// ToType. If such a conversion exists, User will contain the
1544/// user-defined conversion sequence that performs such a conversion
1545/// and this routine will return true. Otherwise, this routine returns
1546/// false and User is unspecified.
1547///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001548/// \param AllowExplicit true if the conversion should consider C++0x
1549/// "explicit" conversion functions as well as non-explicit conversion
1550/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001551OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1552 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001553 OverloadCandidateSet& CandidateSet,
1554 bool AllowExplicit) {
1555 // Whether we will only visit constructors.
1556 bool ConstructorsOnly = false;
1557
1558 // If the type we are conversion to is a class type, enumerate its
1559 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001560 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001561 // C++ [over.match.ctor]p1:
1562 // When objects of class type are direct-initialized (8.5), or
1563 // copy-initialized from an expression of the same or a
1564 // derived class type (8.5), overload resolution selects the
1565 // constructor. [...] For copy-initialization, the candidate
1566 // functions are all the converting constructors (12.3.1) of
1567 // that class. The argument list is the expression-list within
1568 // the parentheses of the initializer.
1569 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1570 (From->getType()->getAs<RecordType>() &&
1571 IsDerivedFrom(From->getType(), ToType)))
1572 ConstructorsOnly = true;
1573
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001574 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1575 // We're not going to find any constructors.
1576 } else if (CXXRecordDecl *ToRecordDecl
1577 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001578 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001579 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001580 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001581 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001582 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001583 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001584 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001585 NamedDecl *D = *Con;
1586 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1587
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001588 // Find the constructor (which may be a template).
1589 CXXConstructorDecl *Constructor = 0;
1590 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001591 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001592 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001593 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001594 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1595 else
John McCalla0296f72010-03-19 07:35:19 +00001596 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001597
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001598 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001599 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001600 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001601 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001602 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001603 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001604 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001605 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001606 // Allow one user-defined conversion when user specifies a
1607 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001608 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001609 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001610 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001611 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001612 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001613 }
1614 }
1615
Douglas Gregor5ab11652010-04-17 22:01:05 +00001616 // Enumerate conversion functions, if we're allowed to.
1617 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001618 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001619 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001620 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001621 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001622 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001623 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001624 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1625 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001626 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001627 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001628 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001629 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001630 DeclAccessPair FoundDecl = I.getPair();
1631 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001632 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1633 if (isa<UsingShadowDecl>(D))
1634 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1635
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001636 CXXConversionDecl *Conv;
1637 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001638 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1639 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001640 else
John McCallda4458e2010-03-31 01:36:47 +00001641 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001642
1643 if (AllowExplicit || !Conv->isExplicit()) {
1644 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001645 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001646 ActingContext, From, ToType,
1647 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001648 else
John McCalla0296f72010-03-19 07:35:19 +00001649 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001650 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001651 }
1652 }
1653 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001654 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001655
1656 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001657 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001658 case OR_Success:
1659 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001660 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001661 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1662 // C++ [over.ics.user]p1:
1663 // If the user-defined conversion is specified by a
1664 // constructor (12.3.1), the initial standard conversion
1665 // sequence converts the source type to the type required by
1666 // the argument of the constructor.
1667 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001668 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001669 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001670 User.EllipsisConversion = true;
1671 else {
1672 User.Before = Best->Conversions[0].Standard;
1673 User.EllipsisConversion = false;
1674 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001675 User.ConversionFunction = Constructor;
1676 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001677 User.After.setFromType(
1678 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001679 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001680 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001681 } else if (CXXConversionDecl *Conversion
1682 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1683 // C++ [over.ics.user]p1:
1684 //
1685 // [...] If the user-defined conversion is specified by a
1686 // conversion function (12.3.2), the initial standard
1687 // conversion sequence converts the source type to the
1688 // implicit object parameter of the conversion function.
1689 User.Before = Best->Conversions[0].Standard;
1690 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001691 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001692
1693 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001694 // The second standard conversion sequence converts the
1695 // result of the user-defined conversion to the target type
1696 // for the sequence. Since an implicit conversion sequence
1697 // is an initialization, the special rules for
1698 // initialization by user-defined conversion apply when
1699 // selecting the best user-defined conversion for a
1700 // user-defined conversion sequence (see 13.3.3 and
1701 // 13.3.3.1).
1702 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001703 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001704 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001705 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001706 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001709 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001710 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001711 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001712 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001713 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001714
1715 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001716 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001717 }
1718
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001719 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001720}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001721
1722bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001723Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001724 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001725 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001726 OverloadingResult OvResult =
1727 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001728 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001729 if (OvResult == OR_Ambiguous)
1730 Diag(From->getSourceRange().getBegin(),
1731 diag::err_typecheck_ambiguous_condition)
1732 << From->getType() << ToType << From->getSourceRange();
1733 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1734 Diag(From->getSourceRange().getBegin(),
1735 diag::err_typecheck_nonviable_condition)
1736 << From->getType() << ToType << From->getSourceRange();
1737 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001738 return false;
John McCallad907772010-01-12 07:18:19 +00001739 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001740 return true;
1741}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001742
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001743/// CompareImplicitConversionSequences - Compare two implicit
1744/// conversion sequences to determine whether one is better than the
1745/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001746ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001747Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1748 const ImplicitConversionSequence& ICS2)
1749{
1750 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1751 // conversion sequences (as defined in 13.3.3.1)
1752 // -- a standard conversion sequence (13.3.3.1.1) is a better
1753 // conversion sequence than a user-defined conversion sequence or
1754 // an ellipsis conversion sequence, and
1755 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1756 // conversion sequence than an ellipsis conversion sequence
1757 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001758 //
John McCall0d1da222010-01-12 00:44:57 +00001759 // C++0x [over.best.ics]p10:
1760 // For the purpose of ranking implicit conversion sequences as
1761 // described in 13.3.3.2, the ambiguous conversion sequence is
1762 // treated as a user-defined sequence that is indistinguishable
1763 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00001764 if (ICS1.getKindRank() < ICS2.getKindRank())
1765 return ImplicitConversionSequence::Better;
1766 else if (ICS2.getKindRank() < ICS1.getKindRank())
1767 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001768
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00001769 // The following checks require both conversion sequences to be of
1770 // the same kind.
1771 if (ICS1.getKind() != ICS2.getKind())
1772 return ImplicitConversionSequence::Indistinguishable;
1773
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001774 // Two implicit conversion sequences of the same form are
1775 // indistinguishable conversion sequences unless one of the
1776 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001777 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001778 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001779 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001780 // User-defined conversion sequence U1 is a better conversion
1781 // sequence than another user-defined conversion sequence U2 if
1782 // they contain the same user-defined conversion function or
1783 // constructor and if the second standard conversion sequence of
1784 // U1 is better than the second standard conversion sequence of
1785 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001786 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001787 ICS2.UserDefined.ConversionFunction)
1788 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1789 ICS2.UserDefined.After);
1790 }
1791
1792 return ImplicitConversionSequence::Indistinguishable;
1793}
1794
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001795// Per 13.3.3.2p3, compare the given standard conversion sequences to
1796// determine if one is a proper subset of the other.
1797static ImplicitConversionSequence::CompareKind
1798compareStandardConversionSubsets(ASTContext &Context,
1799 const StandardConversionSequence& SCS1,
1800 const StandardConversionSequence& SCS2) {
1801 ImplicitConversionSequence::CompareKind Result
1802 = ImplicitConversionSequence::Indistinguishable;
1803
1804 if (SCS1.Second != SCS2.Second) {
1805 if (SCS1.Second == ICK_Identity)
1806 Result = ImplicitConversionSequence::Better;
1807 else if (SCS2.Second == ICK_Identity)
1808 Result = ImplicitConversionSequence::Worse;
1809 else
1810 return ImplicitConversionSequence::Indistinguishable;
1811 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1812 return ImplicitConversionSequence::Indistinguishable;
1813
1814 if (SCS1.Third == SCS2.Third) {
1815 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1816 : ImplicitConversionSequence::Indistinguishable;
1817 }
1818
1819 if (SCS1.Third == ICK_Identity)
1820 return Result == ImplicitConversionSequence::Worse
1821 ? ImplicitConversionSequence::Indistinguishable
1822 : ImplicitConversionSequence::Better;
1823
1824 if (SCS2.Third == ICK_Identity)
1825 return Result == ImplicitConversionSequence::Better
1826 ? ImplicitConversionSequence::Indistinguishable
1827 : ImplicitConversionSequence::Worse;
1828
1829 return ImplicitConversionSequence::Indistinguishable;
1830}
1831
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001832/// CompareStandardConversionSequences - Compare two standard
1833/// conversion sequences to determine whether one is better than the
1834/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001835ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001836Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1837 const StandardConversionSequence& SCS2)
1838{
1839 // Standard conversion sequence S1 is a better conversion sequence
1840 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1841
1842 // -- S1 is a proper subsequence of S2 (comparing the conversion
1843 // sequences in the canonical form defined by 13.3.3.1.1,
1844 // excluding any Lvalue Transformation; the identity conversion
1845 // sequence is considered to be a subsequence of any
1846 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001847 if (ImplicitConversionSequence::CompareKind CK
1848 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1849 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001850
1851 // -- the rank of S1 is better than the rank of S2 (by the rules
1852 // defined below), or, if not that,
1853 ImplicitConversionRank Rank1 = SCS1.getRank();
1854 ImplicitConversionRank Rank2 = SCS2.getRank();
1855 if (Rank1 < Rank2)
1856 return ImplicitConversionSequence::Better;
1857 else if (Rank2 < Rank1)
1858 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001859
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001860 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1861 // are indistinguishable unless one of the following rules
1862 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001863
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001864 // A conversion that is not a conversion of a pointer, or
1865 // pointer to member, to bool is better than another conversion
1866 // that is such a conversion.
1867 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1868 return SCS2.isPointerConversionToBool()
1869 ? ImplicitConversionSequence::Better
1870 : ImplicitConversionSequence::Worse;
1871
Douglas Gregor5c407d92008-10-23 00:40:37 +00001872 // C++ [over.ics.rank]p4b2:
1873 //
1874 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001875 // conversion of B* to A* is better than conversion of B* to
1876 // void*, and conversion of A* to void* is better than conversion
1877 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001878 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001879 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001880 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001881 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001882 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1883 // Exactly one of the conversion sequences is a conversion to
1884 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001885 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1886 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001887 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1888 // Neither conversion sequence converts to a void pointer; compare
1889 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001890 if (ImplicitConversionSequence::CompareKind DerivedCK
1891 = CompareDerivedToBaseConversions(SCS1, SCS2))
1892 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001893 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1894 // Both conversion sequences are conversions to void
1895 // pointers. Compare the source types to determine if there's an
1896 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001897 QualType FromType1 = SCS1.getFromType();
1898 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001899
1900 // Adjust the types we're converting from via the array-to-pointer
1901 // conversion, if we need to.
1902 if (SCS1.First == ICK_Array_To_Pointer)
1903 FromType1 = Context.getArrayDecayedType(FromType1);
1904 if (SCS2.First == ICK_Array_To_Pointer)
1905 FromType2 = Context.getArrayDecayedType(FromType2);
1906
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001907 QualType FromPointee1
1908 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1909 QualType FromPointee2
1910 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001911
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001912 if (IsDerivedFrom(FromPointee2, FromPointee1))
1913 return ImplicitConversionSequence::Better;
1914 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1915 return ImplicitConversionSequence::Worse;
1916
1917 // Objective-C++: If one interface is more specific than the
1918 // other, it is the better one.
1919 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1920 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1921 if (FromIface1 && FromIface1) {
1922 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1923 return ImplicitConversionSequence::Better;
1924 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1925 return ImplicitConversionSequence::Worse;
1926 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001927 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001928
1929 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1930 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001931 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001932 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001933 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001934
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001935 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001936 // C++0x [over.ics.rank]p3b4:
1937 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1938 // implicit object parameter of a non-static member function declared
1939 // without a ref-qualifier, and S1 binds an rvalue reference to an
1940 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001941 // FIXME: We don't know if we're dealing with the implicit object parameter,
1942 // or if the member function in this case has a ref qualifier.
1943 // (Of course, we don't have ref qualifiers yet.)
1944 if (SCS1.RRefBinding != SCS2.RRefBinding)
1945 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1946 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001947
1948 // C++ [over.ics.rank]p3b4:
1949 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1950 // which the references refer are the same type except for
1951 // top-level cv-qualifiers, and the type to which the reference
1952 // initialized by S2 refers is more cv-qualified than the type
1953 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001954 QualType T1 = SCS1.getToType(2);
1955 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001956 T1 = Context.getCanonicalType(T1);
1957 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001958 Qualifiers T1Quals, T2Quals;
1959 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1960 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1961 if (UnqualT1 == UnqualT2) {
1962 // If the type is an array type, promote the element qualifiers to the type
1963 // for comparison.
1964 if (isa<ArrayType>(T1) && T1Quals)
1965 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1966 if (isa<ArrayType>(T2) && T2Quals)
1967 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001968 if (T2.isMoreQualifiedThan(T1))
1969 return ImplicitConversionSequence::Better;
1970 else if (T1.isMoreQualifiedThan(T2))
1971 return ImplicitConversionSequence::Worse;
1972 }
1973 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001974
1975 return ImplicitConversionSequence::Indistinguishable;
1976}
1977
1978/// CompareQualificationConversions - Compares two standard conversion
1979/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001980/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1981ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001982Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001983 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001984 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001985 // -- S1 and S2 differ only in their qualification conversion and
1986 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1987 // cv-qualification signature of type T1 is a proper subset of
1988 // the cv-qualification signature of type T2, and S1 is not the
1989 // deprecated string literal array-to-pointer conversion (4.2).
1990 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1991 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1992 return ImplicitConversionSequence::Indistinguishable;
1993
1994 // FIXME: the example in the standard doesn't use a qualification
1995 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001996 QualType T1 = SCS1.getToType(2);
1997 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001998 T1 = Context.getCanonicalType(T1);
1999 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002000 Qualifiers T1Quals, T2Quals;
2001 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2002 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002003
2004 // If the types are the same, we won't learn anything by unwrapped
2005 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002006 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002007 return ImplicitConversionSequence::Indistinguishable;
2008
Chandler Carruth607f38e2009-12-29 07:16:59 +00002009 // If the type is an array type, promote the element qualifiers to the type
2010 // for comparison.
2011 if (isa<ArrayType>(T1) && T1Quals)
2012 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2013 if (isa<ArrayType>(T2) && T2Quals)
2014 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2015
Mike Stump11289f42009-09-09 15:08:12 +00002016 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002017 = ImplicitConversionSequence::Indistinguishable;
2018 while (UnwrapSimilarPointerTypes(T1, T2)) {
2019 // Within each iteration of the loop, we check the qualifiers to
2020 // determine if this still looks like a qualification
2021 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002022 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002023 // until there are no more pointers or pointers-to-members left
2024 // to unwrap. This essentially mimics what
2025 // IsQualificationConversion does, but here we're checking for a
2026 // strict subset of qualifiers.
2027 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2028 // The qualifiers are the same, so this doesn't tell us anything
2029 // about how the sequences rank.
2030 ;
2031 else if (T2.isMoreQualifiedThan(T1)) {
2032 // T1 has fewer qualifiers, so it could be the better sequence.
2033 if (Result == ImplicitConversionSequence::Worse)
2034 // Neither has qualifiers that are a subset of the other's
2035 // qualifiers.
2036 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002037
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002038 Result = ImplicitConversionSequence::Better;
2039 } else if (T1.isMoreQualifiedThan(T2)) {
2040 // T2 has fewer qualifiers, so it could be the better sequence.
2041 if (Result == ImplicitConversionSequence::Better)
2042 // Neither has qualifiers that are a subset of the other's
2043 // qualifiers.
2044 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002045
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002046 Result = ImplicitConversionSequence::Worse;
2047 } else {
2048 // Qualifiers are disjoint.
2049 return ImplicitConversionSequence::Indistinguishable;
2050 }
2051
2052 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002053 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002054 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002055 }
2056
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002057 // Check that the winning standard conversion sequence isn't using
2058 // the deprecated string literal array to pointer conversion.
2059 switch (Result) {
2060 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002061 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002062 Result = ImplicitConversionSequence::Indistinguishable;
2063 break;
2064
2065 case ImplicitConversionSequence::Indistinguishable:
2066 break;
2067
2068 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002069 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002070 Result = ImplicitConversionSequence::Indistinguishable;
2071 break;
2072 }
2073
2074 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002075}
2076
Douglas Gregor5c407d92008-10-23 00:40:37 +00002077/// CompareDerivedToBaseConversions - Compares two standard conversion
2078/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002079/// various kinds of derived-to-base conversions (C++
2080/// [over.ics.rank]p4b3). As part of these checks, we also look at
2081/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002082ImplicitConversionSequence::CompareKind
2083Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2084 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002085 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002086 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002087 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002088 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002089
2090 // Adjust the types we're converting from via the array-to-pointer
2091 // conversion, if we need to.
2092 if (SCS1.First == ICK_Array_To_Pointer)
2093 FromType1 = Context.getArrayDecayedType(FromType1);
2094 if (SCS2.First == ICK_Array_To_Pointer)
2095 FromType2 = Context.getArrayDecayedType(FromType2);
2096
2097 // Canonicalize all of the types.
2098 FromType1 = Context.getCanonicalType(FromType1);
2099 ToType1 = Context.getCanonicalType(ToType1);
2100 FromType2 = Context.getCanonicalType(FromType2);
2101 ToType2 = Context.getCanonicalType(ToType2);
2102
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002103 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002104 //
2105 // If class B is derived directly or indirectly from class A and
2106 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002107 //
2108 // For Objective-C, we let A, B, and C also be Objective-C
2109 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002110
2111 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002112 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002113 SCS2.Second == ICK_Pointer_Conversion &&
2114 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2115 FromType1->isPointerType() && FromType2->isPointerType() &&
2116 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002117 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002118 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002119 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002120 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002121 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002122 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002123 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002124 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002125
John McCall9dd450b2009-09-21 23:43:11 +00002126 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2127 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2128 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2129 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002130
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002131 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002132 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2133 if (IsDerivedFrom(ToPointee1, ToPointee2))
2134 return ImplicitConversionSequence::Better;
2135 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2136 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002137
2138 if (ToIface1 && ToIface2) {
2139 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2140 return ImplicitConversionSequence::Better;
2141 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2142 return ImplicitConversionSequence::Worse;
2143 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002144 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002145
2146 // -- conversion of B* to A* is better than conversion of C* to A*,
2147 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2148 if (IsDerivedFrom(FromPointee2, FromPointee1))
2149 return ImplicitConversionSequence::Better;
2150 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2151 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002152
Douglas Gregor237f96c2008-11-26 23:31:11 +00002153 if (FromIface1 && FromIface2) {
2154 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2155 return ImplicitConversionSequence::Better;
2156 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2157 return ImplicitConversionSequence::Worse;
2158 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002159 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002160 }
2161
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002162 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002163 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2164 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2165 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2166 const MemberPointerType * FromMemPointer1 =
2167 FromType1->getAs<MemberPointerType>();
2168 const MemberPointerType * ToMemPointer1 =
2169 ToType1->getAs<MemberPointerType>();
2170 const MemberPointerType * FromMemPointer2 =
2171 FromType2->getAs<MemberPointerType>();
2172 const MemberPointerType * ToMemPointer2 =
2173 ToType2->getAs<MemberPointerType>();
2174 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2175 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2176 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2177 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2178 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2179 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2180 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2181 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002182 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002183 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2184 if (IsDerivedFrom(ToPointee1, ToPointee2))
2185 return ImplicitConversionSequence::Worse;
2186 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2187 return ImplicitConversionSequence::Better;
2188 }
2189 // conversion of B::* to C::* is better than conversion of A::* to C::*
2190 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2191 if (IsDerivedFrom(FromPointee1, FromPointee2))
2192 return ImplicitConversionSequence::Better;
2193 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2194 return ImplicitConversionSequence::Worse;
2195 }
2196 }
2197
Douglas Gregor5ab11652010-04-17 22:01:05 +00002198 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002199 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002200 // -- binding of an expression of type C to a reference of type
2201 // B& is better than binding an expression of type C to a
2202 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002203 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2204 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002205 if (IsDerivedFrom(ToType1, ToType2))
2206 return ImplicitConversionSequence::Better;
2207 else if (IsDerivedFrom(ToType2, ToType1))
2208 return ImplicitConversionSequence::Worse;
2209 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002210
Douglas Gregor2fe98832008-11-03 19:09:14 +00002211 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002212 // -- binding of an expression of type B to a reference of type
2213 // A& is better than binding an expression of type C to a
2214 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002215 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2216 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002217 if (IsDerivedFrom(FromType2, FromType1))
2218 return ImplicitConversionSequence::Better;
2219 else if (IsDerivedFrom(FromType1, FromType2))
2220 return ImplicitConversionSequence::Worse;
2221 }
2222 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002223
Douglas Gregor5c407d92008-10-23 00:40:37 +00002224 return ImplicitConversionSequence::Indistinguishable;
2225}
2226
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002227/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2228/// determine whether they are reference-related,
2229/// reference-compatible, reference-compatible with added
2230/// qualification, or incompatible, for use in C++ initialization by
2231/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2232/// type, and the first type (T1) is the pointee type of the reference
2233/// type being initialized.
2234Sema::ReferenceCompareResult
2235Sema::CompareReferenceRelationship(SourceLocation Loc,
2236 QualType OrigT1, QualType OrigT2,
2237 bool& DerivedToBase) {
2238 assert(!OrigT1->isReferenceType() &&
2239 "T1 must be the pointee type of the reference type");
2240 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2241
2242 QualType T1 = Context.getCanonicalType(OrigT1);
2243 QualType T2 = Context.getCanonicalType(OrigT2);
2244 Qualifiers T1Quals, T2Quals;
2245 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2246 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2247
2248 // C++ [dcl.init.ref]p4:
2249 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2250 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2251 // T1 is a base class of T2.
2252 if (UnqualT1 == UnqualT2)
2253 DerivedToBase = false;
2254 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
2255 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
2256 IsDerivedFrom(UnqualT2, UnqualT1))
2257 DerivedToBase = true;
2258 else
2259 return Ref_Incompatible;
2260
2261 // At this point, we know that T1 and T2 are reference-related (at
2262 // least).
2263
2264 // If the type is an array type, promote the element qualifiers to the type
2265 // for comparison.
2266 if (isa<ArrayType>(T1) && T1Quals)
2267 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2268 if (isa<ArrayType>(T2) && T2Quals)
2269 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2270
2271 // C++ [dcl.init.ref]p4:
2272 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2273 // reference-related to T2 and cv1 is the same cv-qualification
2274 // as, or greater cv-qualification than, cv2. For purposes of
2275 // overload resolution, cases for which cv1 is greater
2276 // cv-qualification than cv2 are identified as
2277 // reference-compatible with added qualification (see 13.3.3.2).
2278 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2279 return Ref_Compatible;
2280 else if (T1.isMoreQualifiedThan(T2))
2281 return Ref_Compatible_With_Added_Qualification;
2282 else
2283 return Ref_Related;
2284}
2285
2286/// \brief Compute an implicit conversion sequence for reference
2287/// initialization.
2288static ImplicitConversionSequence
2289TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2290 SourceLocation DeclLoc,
2291 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002292 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002293 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2294
2295 // Most paths end in a failed conversion.
2296 ImplicitConversionSequence ICS;
2297 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2298
2299 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2300 QualType T2 = Init->getType();
2301
2302 // If the initializer is the address of an overloaded function, try
2303 // to resolve the overloaded function. If all goes well, T2 is the
2304 // type of the resulting function.
2305 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2306 DeclAccessPair Found;
2307 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2308 false, Found))
2309 T2 = Fn->getType();
2310 }
2311
2312 // Compute some basic properties of the types and the initializer.
2313 bool isRValRef = DeclType->isRValueReferenceType();
2314 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002315 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002316 Sema::ReferenceCompareResult RefRelationship
2317 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2318
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002319
2320 // C++ [over.ics.ref]p3:
2321 // Except for an implicit object parameter, for which see 13.3.1,
2322 // a standard conversion sequence cannot be formed if it requires
2323 // binding an lvalue reference to non-const to an rvalue or
2324 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002325 //
2326 // FIXME: DPG doesn't trust this code. It seems far too early to
2327 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002328 if (isRValRef && InitLvalue == Expr::LV_Valid)
2329 return ICS;
2330
Douglas Gregor870f3742010-04-18 09:22:00 +00002331 // C++0x [dcl.init.ref]p16:
2332 // A reference to type "cv1 T1" is initialized by an expression
2333 // of type "cv2 T2" as follows:
2334
2335 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002336 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2337 // reference-compatible with "cv2 T2," or
2338 //
2339 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2340 if (InitLvalue == Expr::LV_Valid &&
2341 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2342 // C++ [over.ics.ref]p1:
2343 // When a parameter of reference type binds directly (8.5.3)
2344 // to an argument expression, the implicit conversion sequence
2345 // is the identity conversion, unless the argument expression
2346 // has a type that is a derived class of the parameter type,
2347 // in which case the implicit conversion sequence is a
2348 // derived-to-base Conversion (13.3.3.1).
2349 ICS.setStandard();
2350 ICS.Standard.First = ICK_Identity;
2351 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2352 ICS.Standard.Third = ICK_Identity;
2353 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2354 ICS.Standard.setToType(0, T2);
2355 ICS.Standard.setToType(1, T1);
2356 ICS.Standard.setToType(2, T1);
2357 ICS.Standard.ReferenceBinding = true;
2358 ICS.Standard.DirectBinding = true;
2359 ICS.Standard.RRefBinding = false;
2360 ICS.Standard.CopyConstructor = 0;
2361
2362 // Nothing more to do: the inaccessibility/ambiguity check for
2363 // derived-to-base conversions is suppressed when we're
2364 // computing the implicit conversion sequence (C++
2365 // [over.best.ics]p2).
2366 return ICS;
2367 }
2368
2369 // -- has a class type (i.e., T2 is a class type), where T1 is
2370 // not reference-related to T2, and can be implicitly
2371 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2372 // is reference-compatible with "cv3 T3" 92) (this
2373 // conversion is selected by enumerating the applicable
2374 // conversion functions (13.3.1.6) and choosing the best
2375 // one through overload resolution (13.3)),
2376 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2377 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2378 RefRelationship == Sema::Ref_Incompatible) {
2379 CXXRecordDecl *T2RecordDecl
2380 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2381
2382 OverloadCandidateSet CandidateSet(DeclLoc);
2383 const UnresolvedSetImpl *Conversions
2384 = T2RecordDecl->getVisibleConversionFunctions();
2385 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2386 E = Conversions->end(); I != E; ++I) {
2387 NamedDecl *D = *I;
2388 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2389 if (isa<UsingShadowDecl>(D))
2390 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2391
2392 FunctionTemplateDecl *ConvTemplate
2393 = dyn_cast<FunctionTemplateDecl>(D);
2394 CXXConversionDecl *Conv;
2395 if (ConvTemplate)
2396 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2397 else
2398 Conv = cast<CXXConversionDecl>(D);
2399
2400 // If the conversion function doesn't return a reference type,
2401 // it can't be considered for this conversion.
2402 if (Conv->getConversionType()->isLValueReferenceType() &&
2403 (AllowExplicit || !Conv->isExplicit())) {
2404 if (ConvTemplate)
2405 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2406 Init, DeclType, CandidateSet);
2407 else
2408 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2409 DeclType, CandidateSet);
2410 }
2411 }
2412
2413 OverloadCandidateSet::iterator Best;
2414 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2415 case OR_Success:
2416 // C++ [over.ics.ref]p1:
2417 //
2418 // [...] If the parameter binds directly to the result of
2419 // applying a conversion function to the argument
2420 // expression, the implicit conversion sequence is a
2421 // user-defined conversion sequence (13.3.3.1.2), with the
2422 // second standard conversion sequence either an identity
2423 // conversion or, if the conversion function returns an
2424 // entity of a type that is a derived class of the parameter
2425 // type, a derived-to-base Conversion.
2426 if (!Best->FinalConversion.DirectBinding)
2427 break;
2428
2429 ICS.setUserDefined();
2430 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2431 ICS.UserDefined.After = Best->FinalConversion;
2432 ICS.UserDefined.ConversionFunction = Best->Function;
2433 ICS.UserDefined.EllipsisConversion = false;
2434 assert(ICS.UserDefined.After.ReferenceBinding &&
2435 ICS.UserDefined.After.DirectBinding &&
2436 "Expected a direct reference binding!");
2437 return ICS;
2438
2439 case OR_Ambiguous:
2440 ICS.setAmbiguous();
2441 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2442 Cand != CandidateSet.end(); ++Cand)
2443 if (Cand->Viable)
2444 ICS.Ambiguous.addConversion(Cand->Function);
2445 return ICS;
2446
2447 case OR_No_Viable_Function:
2448 case OR_Deleted:
2449 // There was no suitable conversion, or we found a deleted
2450 // conversion; continue with other checks.
2451 break;
2452 }
2453 }
2454
2455 // -- Otherwise, the reference shall be to a non-volatile const
2456 // type (i.e., cv1 shall be const), or the reference shall be an
2457 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002458 //
2459 // We actually handle one oddity of C++ [over.ics.ref] at this
2460 // point, which is that, due to p2 (which short-circuits reference
2461 // binding by only attempting a simple conversion for non-direct
2462 // bindings) and p3's strange wording, we allow a const volatile
2463 // reference to bind to an rvalue. Hence the check for the presence
2464 // of "const" rather than checking for "const" being the only
2465 // qualifier.
2466 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002467 return ICS;
2468
Douglas Gregorf93df192010-04-18 08:46:23 +00002469 // -- if T2 is a class type and
2470 // -- the initializer expression is an rvalue and "cv1 T1"
2471 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002472 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002473 // -- T1 is not reference-related to T2 and the initializer
2474 // expression can be implicitly converted to an rvalue
2475 // of type "cv3 T3" (this conversion is selected by
2476 // enumerating the applicable conversion functions
2477 // (13.3.1.6) and choosing the best one through overload
2478 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002479 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002480 // then the reference is bound to the initializer
2481 // expression rvalue in the first case and to the object
2482 // that is the result of the conversion in the second case
2483 // (or, in either case, to the appropriate base class
2484 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002485 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002486 // We're only checking the first case here, which is a direct
2487 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002488 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2489 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2490 ICS.setStandard();
2491 ICS.Standard.First = ICK_Identity;
2492 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2493 ICS.Standard.Third = ICK_Identity;
2494 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2495 ICS.Standard.setToType(0, T2);
2496 ICS.Standard.setToType(1, T1);
2497 ICS.Standard.setToType(2, T1);
2498 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002499 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002500 ICS.Standard.RRefBinding = isRValRef;
2501 ICS.Standard.CopyConstructor = 0;
2502 return ICS;
2503 }
2504
2505 // -- Otherwise, a temporary of type "cv1 T1" is created and
2506 // initialized from the initializer expression using the
2507 // rules for a non-reference copy initialization (8.5). The
2508 // reference is then bound to the temporary. If T1 is
2509 // reference-related to T2, cv1 must be the same
2510 // cv-qualification as, or greater cv-qualification than,
2511 // cv2; otherwise, the program is ill-formed.
2512 if (RefRelationship == Sema::Ref_Related) {
2513 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2514 // we would be reference-compatible or reference-compatible with
2515 // added qualification. But that wasn't the case, so the reference
2516 // initialization fails.
2517 return ICS;
2518 }
2519
2520 // If at least one of the types is a class type, the types are not
2521 // related, and we aren't allowed any user conversions, the
2522 // reference binding fails. This case is important for breaking
2523 // recursion, since TryImplicitConversion below will attempt to
2524 // create a temporary through the use of a copy constructor.
2525 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2526 (T1->isRecordType() || T2->isRecordType()))
2527 return ICS;
2528
2529 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002530 // When a parameter of reference type is not bound directly to
2531 // an argument expression, the conversion sequence is the one
2532 // required to convert the argument expression to the
2533 // underlying type of the reference according to
2534 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2535 // to copy-initializing a temporary of the underlying type with
2536 // the argument expression. Any difference in top-level
2537 // cv-qualification is subsumed by the initialization itself
2538 // and does not constitute a conversion.
2539 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2540 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002541 /*InOverloadResolution=*/false);
2542
2543 // Of course, that's still a reference binding.
2544 if (ICS.isStandard()) {
2545 ICS.Standard.ReferenceBinding = true;
2546 ICS.Standard.RRefBinding = isRValRef;
2547 } else if (ICS.isUserDefined()) {
2548 ICS.UserDefined.After.ReferenceBinding = true;
2549 ICS.UserDefined.After.RRefBinding = isRValRef;
2550 }
2551 return ICS;
2552}
2553
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002554/// TryCopyInitialization - Try to copy-initialize a value of type
2555/// ToType from the expression From. Return the implicit conversion
2556/// sequence required to pass this argument, which may be a bad
2557/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002558/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002559/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002560static ImplicitConversionSequence
2561TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002562 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002563 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002564 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002565 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002566 /*FIXME:*/From->getLocStart(),
2567 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002568 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002569
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002570 return S.TryImplicitConversion(From, ToType,
2571 SuppressUserConversions,
2572 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002573 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002574}
2575
Douglas Gregor436424c2008-11-18 23:14:02 +00002576/// TryObjectArgumentInitialization - Try to initialize the object
2577/// parameter of the given member function (@c Method) from the
2578/// expression @p From.
2579ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002580Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002581 CXXMethodDecl *Method,
2582 CXXRecordDecl *ActingContext) {
2583 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002584 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2585 // const volatile object.
2586 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2587 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2588 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002589
2590 // Set up the conversion sequence as a "bad" conversion, to allow us
2591 // to exit early.
2592 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002593
2594 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002595 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002596 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002597 FromType = PT->getPointeeType();
2598
2599 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002600
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002601 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002602 // where X is the class of which the function is a member
2603 // (C++ [over.match.funcs]p4). However, when finding an implicit
2604 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002605 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002606 // (C++ [over.match.funcs]p5). We perform a simplified version of
2607 // reference binding here, that allows class rvalues to bind to
2608 // non-constant references.
2609
2610 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2611 // with the implicit object parameter (C++ [over.match.funcs]p5).
2612 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002613 if (ImplicitParamType.getCVRQualifiers()
2614 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002615 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002616 ICS.setBad(BadConversionSequence::bad_qualifiers,
2617 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002618 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002619 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002620
2621 // Check that we have either the same type or a derived type. It
2622 // affects the conversion rank.
2623 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002624 ImplicitConversionKind SecondKind;
2625 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2626 SecondKind = ICK_Identity;
2627 } else if (IsDerivedFrom(FromType, ClassType))
2628 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002629 else {
John McCall65eb8792010-02-25 01:37:24 +00002630 ICS.setBad(BadConversionSequence::unrelated_class,
2631 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002632 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002633 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002634
2635 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002636 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002637 ICS.Standard.setAsIdentityConversion();
2638 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002639 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002640 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002641 ICS.Standard.ReferenceBinding = true;
2642 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002643 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002644 return ICS;
2645}
2646
2647/// PerformObjectArgumentInitialization - Perform initialization of
2648/// the implicit object parameter for the given Method with the given
2649/// expression.
2650bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002651Sema::PerformObjectArgumentInitialization(Expr *&From,
2652 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002653 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002654 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002655 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002656 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002657 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002658
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002659 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002660 FromRecordType = PT->getPointeeType();
2661 DestType = Method->getThisType(Context);
2662 } else {
2663 FromRecordType = From->getType();
2664 DestType = ImplicitParamRecordType;
2665 }
2666
John McCall6e9f8f62009-12-03 04:06:58 +00002667 // Note that we always use the true parent context when performing
2668 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002669 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002670 = TryObjectArgumentInitialization(From->getType(), Method,
2671 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002672 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002673 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002674 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002675 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002676
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002677 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002678 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002679
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002680 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002681 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2682 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002683 return false;
2684}
2685
Douglas Gregor5fb53972009-01-14 15:45:31 +00002686/// TryContextuallyConvertToBool - Attempt to contextually convert the
2687/// expression From to bool (C++0x [conv]p3).
2688ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002689 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002690 // FIXME: Are these flags correct?
2691 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002692 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002693 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002694}
2695
2696/// PerformContextuallyConvertToBool - Perform a contextual conversion
2697/// of the expression From to bool (C++0x [conv]p3).
2698bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2699 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002700 if (!ICS.isBad())
2701 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002702
Fariborz Jahanian76197412009-11-18 18:26:29 +00002703 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002704 return Diag(From->getSourceRange().getBegin(),
2705 diag::err_typecheck_bool_condition)
2706 << From->getType() << From->getSourceRange();
2707 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002708}
2709
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002710/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002711/// candidate functions, using the given function call arguments. If
2712/// @p SuppressUserConversions, then don't allow user-defined
2713/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002714///
2715/// \para PartialOverloading true if we are performing "partial" overloading
2716/// based on an incomplete set of function arguments. This feature is used by
2717/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002718void
2719Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002720 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002721 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002722 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002723 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002724 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002725 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002726 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002727 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002728 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002729 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002730
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002731 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002732 if (!isa<CXXConstructorDecl>(Method)) {
2733 // If we get here, it's because we're calling a member function
2734 // that is named without a member access expression (e.g.,
2735 // "this->f") that was either written explicitly or created
2736 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002737 // function, e.g., X::f(). We use an empty type for the implied
2738 // object argument (C++ [over.call.func]p3), and the acting context
2739 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002740 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002741 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002742 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002743 return;
2744 }
2745 // We treat a constructor like a non-member function, since its object
2746 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002747 }
2748
Douglas Gregorff7028a2009-11-13 23:59:09 +00002749 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002750 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002751
Douglas Gregor27381f32009-11-23 12:27:39 +00002752 // Overload resolution is always an unevaluated context.
2753 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2754
Douglas Gregorffe14e32009-11-14 01:20:54 +00002755 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2756 // C++ [class.copy]p3:
2757 // A member function template is never instantiated to perform the copy
2758 // of a class object to an object of its class type.
2759 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2760 if (NumArgs == 1 &&
2761 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002762 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2763 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002764 return;
2765 }
2766
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002767 // Add this candidate
2768 CandidateSet.push_back(OverloadCandidate());
2769 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002770 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002771 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002772 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002773 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002774 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002775
2776 unsigned NumArgsInProto = Proto->getNumArgs();
2777
2778 // (C++ 13.3.2p2): A candidate function having fewer than m
2779 // parameters is viable only if it has an ellipsis in its parameter
2780 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002781 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2782 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002783 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002784 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002785 return;
2786 }
2787
2788 // (C++ 13.3.2p2): A candidate function having more than m parameters
2789 // is viable only if the (m+1)st parameter has a default argument
2790 // (8.3.6). For the purposes of overload resolution, the
2791 // parameter list is truncated on the right, so that there are
2792 // exactly m parameters.
2793 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002794 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002795 // Not enough arguments.
2796 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002797 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002798 return;
2799 }
2800
2801 // Determine the implicit conversion sequences for each of the
2802 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002803 Candidate.Conversions.resize(NumArgs);
2804 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2805 if (ArgIdx < NumArgsInProto) {
2806 // (C++ 13.3.2p3): for F to be a viable function, there shall
2807 // exist for each argument an implicit conversion sequence
2808 // (13.3.3.1) that converts that argument to the corresponding
2809 // parameter of F.
2810 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002811 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002812 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002813 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00002814 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002815 if (Candidate.Conversions[ArgIdx].isBad()) {
2816 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002817 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002818 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002819 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002820 } else {
2821 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2822 // argument for which there is no corresponding parameter is
2823 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002824 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002825 }
2826 }
2827}
2828
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002829/// \brief Add all of the function declarations in the given function set to
2830/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002831void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002832 Expr **Args, unsigned NumArgs,
2833 OverloadCandidateSet& CandidateSet,
2834 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002835 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00002836 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2837 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002838 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002839 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002840 cast<CXXMethodDecl>(FD)->getParent(),
2841 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002842 CandidateSet, SuppressUserConversions);
2843 else
John McCalla0296f72010-03-19 07:35:19 +00002844 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002845 SuppressUserConversions);
2846 } else {
John McCalla0296f72010-03-19 07:35:19 +00002847 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002848 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2849 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002850 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002851 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002852 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002853 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002854 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002855 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002856 else
John McCalla0296f72010-03-19 07:35:19 +00002857 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00002858 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002859 Args, NumArgs, CandidateSet,
2860 SuppressUserConversions);
2861 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002862 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002863}
2864
John McCallf0f1cf02009-11-17 07:50:12 +00002865/// AddMethodCandidate - Adds a named decl (which is some kind of
2866/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00002867void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002868 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002869 Expr **Args, unsigned NumArgs,
2870 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002871 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00002872 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002873 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002874
2875 if (isa<UsingShadowDecl>(Decl))
2876 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2877
2878 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2879 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2880 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00002881 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2882 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002883 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002884 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002885 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002886 } else {
John McCalla0296f72010-03-19 07:35:19 +00002887 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002888 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002889 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002890 }
2891}
2892
Douglas Gregor436424c2008-11-18 23:14:02 +00002893/// AddMethodCandidate - Adds the given C++ member function to the set
2894/// of candidate functions, using the given function call arguments
2895/// and the object argument (@c Object). For example, in a call
2896/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2897/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2898/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00002899/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00002900void
John McCalla0296f72010-03-19 07:35:19 +00002901Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002902 CXXRecordDecl *ActingContext, QualType ObjectType,
2903 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002904 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002905 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002906 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002907 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002908 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002909 assert(!isa<CXXConstructorDecl>(Method) &&
2910 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002911
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002912 if (!CandidateSet.isNewCandidate(Method))
2913 return;
2914
Douglas Gregor27381f32009-11-23 12:27:39 +00002915 // Overload resolution is always an unevaluated context.
2916 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2917
Douglas Gregor436424c2008-11-18 23:14:02 +00002918 // Add this candidate
2919 CandidateSet.push_back(OverloadCandidate());
2920 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002921 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00002922 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002923 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002924 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002925
2926 unsigned NumArgsInProto = Proto->getNumArgs();
2927
2928 // (C++ 13.3.2p2): A candidate function having fewer than m
2929 // parameters is viable only if it has an ellipsis in its parameter
2930 // list (8.3.5).
2931 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2932 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002933 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002934 return;
2935 }
2936
2937 // (C++ 13.3.2p2): A candidate function having more than m parameters
2938 // is viable only if the (m+1)st parameter has a default argument
2939 // (8.3.6). For the purposes of overload resolution, the
2940 // parameter list is truncated on the right, so that there are
2941 // exactly m parameters.
2942 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2943 if (NumArgs < MinRequiredArgs) {
2944 // Not enough arguments.
2945 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002946 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002947 return;
2948 }
2949
2950 Candidate.Viable = true;
2951 Candidate.Conversions.resize(NumArgs + 1);
2952
John McCall6e9f8f62009-12-03 04:06:58 +00002953 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002954 // The implicit object argument is ignored.
2955 Candidate.IgnoreObjectArgument = true;
2956 else {
2957 // Determine the implicit conversion sequence for the object
2958 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002959 Candidate.Conversions[0]
2960 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002961 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002962 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002963 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002964 return;
2965 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002966 }
2967
2968 // Determine the implicit conversion sequences for each of the
2969 // arguments.
2970 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2971 if (ArgIdx < NumArgsInProto) {
2972 // (C++ 13.3.2p3): for F to be a viable function, there shall
2973 // exist for each argument an implicit conversion sequence
2974 // (13.3.3.1) that converts that argument to the corresponding
2975 // parameter of F.
2976 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002977 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002978 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002979 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00002980 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002981 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002982 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002983 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002984 break;
2985 }
2986 } else {
2987 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2988 // argument for which there is no corresponding parameter is
2989 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002990 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002991 }
2992 }
2993}
2994
Douglas Gregor97628d62009-08-21 00:16:32 +00002995/// \brief Add a C++ member function template as a candidate to the candidate
2996/// set, using template argument deduction to produce an appropriate member
2997/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002998void
Douglas Gregor97628d62009-08-21 00:16:32 +00002999Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003000 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003001 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003002 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003003 QualType ObjectType,
3004 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003005 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003006 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003007 if (!CandidateSet.isNewCandidate(MethodTmpl))
3008 return;
3009
Douglas Gregor97628d62009-08-21 00:16:32 +00003010 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003011 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003012 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003013 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003014 // candidate functions in the usual way.113) A given name can refer to one
3015 // or more function templates and also to a set of overloaded non-template
3016 // functions. In such a case, the candidate functions generated from each
3017 // function template are combined with the set of non-template candidate
3018 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003019 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003020 FunctionDecl *Specialization = 0;
3021 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003022 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003023 Args, NumArgs, Specialization, Info)) {
3024 // FIXME: Record what happened with template argument deduction, so
3025 // that we can give the user a beautiful diagnostic.
3026 (void)Result;
3027 return;
3028 }
Mike Stump11289f42009-09-09 15:08:12 +00003029
Douglas Gregor97628d62009-08-21 00:16:32 +00003030 // Add the function template specialization produced by template argument
3031 // deduction as a candidate.
3032 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003033 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003034 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003035 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003036 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003037 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003038}
3039
Douglas Gregor05155d82009-08-21 23:19:43 +00003040/// \brief Add a C++ function template specialization as a candidate
3041/// in the candidate set, using template argument deduction to produce
3042/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003043void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003044Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003045 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003046 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003047 Expr **Args, unsigned NumArgs,
3048 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003049 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003050 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3051 return;
3052
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003053 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003054 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003055 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003056 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003057 // candidate functions in the usual way.113) A given name can refer to one
3058 // or more function templates and also to a set of overloaded non-template
3059 // functions. In such a case, the candidate functions generated from each
3060 // function template are combined with the set of non-template candidate
3061 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003062 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003063 FunctionDecl *Specialization = 0;
3064 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003065 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003066 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003067 CandidateSet.push_back(OverloadCandidate());
3068 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003069 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003070 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3071 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003072 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003073 Candidate.IsSurrogate = false;
3074 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00003075
3076 // TODO: record more information about failed template arguments
3077 Candidate.DeductionFailure.Result = Result;
3078 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003079 return;
3080 }
Mike Stump11289f42009-09-09 15:08:12 +00003081
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003082 // Add the function template specialization produced by template argument
3083 // deduction as a candidate.
3084 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003085 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003086 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003087}
Mike Stump11289f42009-09-09 15:08:12 +00003088
Douglas Gregora1f013e2008-11-07 22:36:19 +00003089/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003090/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003091/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003092/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003093/// (which may or may not be the same type as the type that the
3094/// conversion function produces).
3095void
3096Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003097 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003098 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003099 Expr *From, QualType ToType,
3100 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003101 assert(!Conversion->getDescribedFunctionTemplate() &&
3102 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003103 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003104 if (!CandidateSet.isNewCandidate(Conversion))
3105 return;
3106
Douglas Gregor27381f32009-11-23 12:27:39 +00003107 // Overload resolution is always an unevaluated context.
3108 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3109
Douglas Gregora1f013e2008-11-07 22:36:19 +00003110 // Add this candidate
3111 CandidateSet.push_back(OverloadCandidate());
3112 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003113 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003114 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003115 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003116 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003117 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003118 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003119 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003120
Douglas Gregor436424c2008-11-18 23:14:02 +00003121 // Determine the implicit conversion sequence for the implicit
3122 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003123 Candidate.Viable = true;
3124 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003125 Candidate.Conversions[0]
3126 = TryObjectArgumentInitialization(From->getType(), Conversion,
3127 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003128 // Conversion functions to a different type in the base class is visible in
3129 // the derived class. So, a derived to base conversion should not participate
3130 // in overload resolution.
3131 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3132 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003133 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003134 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003135 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003136 return;
3137 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003138
3139 // We won't go through a user-define type conversion function to convert a
3140 // derived to base as such conversions are given Conversion Rank. They only
3141 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3142 QualType FromCanon
3143 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3144 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3145 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3146 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003147 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003148 return;
3149 }
3150
Douglas Gregora1f013e2008-11-07 22:36:19 +00003151 // To determine what the conversion from the result of calling the
3152 // conversion function to the type we're eventually trying to
3153 // convert to (ToType), we need to synthesize a call to the
3154 // conversion function and attempt copy initialization from it. This
3155 // makes sure that we get the right semantics with respect to
3156 // lvalues/rvalues and the type. Fortunately, we can allocate this
3157 // call on the stack and we don't need its arguments to be
3158 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003159 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003160 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003161 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003162 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003163 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003164
3165 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003166 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3167 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003168 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003169 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003170 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003171 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003172 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003173 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003174 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003175
John McCall0d1da222010-01-12 00:44:57 +00003176 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003177 case ImplicitConversionSequence::StandardConversion:
3178 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003179
3180 // C++ [over.ics.user]p3:
3181 // If the user-defined conversion is specified by a specialization of a
3182 // conversion function template, the second standard conversion sequence
3183 // shall have exact match rank.
3184 if (Conversion->getPrimaryTemplate() &&
3185 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3186 Candidate.Viable = false;
3187 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3188 }
3189
Douglas Gregora1f013e2008-11-07 22:36:19 +00003190 break;
3191
3192 case ImplicitConversionSequence::BadConversion:
3193 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003194 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003195 break;
3196
3197 default:
Mike Stump11289f42009-09-09 15:08:12 +00003198 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003199 "Can only end up with a standard conversion sequence or failure");
3200 }
3201}
3202
Douglas Gregor05155d82009-08-21 23:19:43 +00003203/// \brief Adds a conversion function template specialization
3204/// candidate to the overload set, using template argument deduction
3205/// to deduce the template arguments of the conversion function
3206/// template from the type that we are converting to (C++
3207/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003208void
Douglas Gregor05155d82009-08-21 23:19:43 +00003209Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003210 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003211 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003212 Expr *From, QualType ToType,
3213 OverloadCandidateSet &CandidateSet) {
3214 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3215 "Only conversion function templates permitted here");
3216
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003217 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3218 return;
3219
John McCallbc077cf2010-02-08 23:07:23 +00003220 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003221 CXXConversionDecl *Specialization = 0;
3222 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003223 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003224 Specialization, Info)) {
3225 // FIXME: Record what happened with template argument deduction, so
3226 // that we can give the user a beautiful diagnostic.
3227 (void)Result;
3228 return;
3229 }
Mike Stump11289f42009-09-09 15:08:12 +00003230
Douglas Gregor05155d82009-08-21 23:19:43 +00003231 // Add the conversion function template specialization produced by
3232 // template argument deduction as a candidate.
3233 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003234 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003235 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003236}
3237
Douglas Gregorab7897a2008-11-19 22:57:39 +00003238/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3239/// converts the given @c Object to a function pointer via the
3240/// conversion function @c Conversion, and then attempts to call it
3241/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3242/// the type of function that we'll eventually be calling.
3243void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003244 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003245 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003246 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003247 QualType ObjectType,
3248 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003249 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003250 if (!CandidateSet.isNewCandidate(Conversion))
3251 return;
3252
Douglas Gregor27381f32009-11-23 12:27:39 +00003253 // Overload resolution is always an unevaluated context.
3254 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3255
Douglas Gregorab7897a2008-11-19 22:57:39 +00003256 CandidateSet.push_back(OverloadCandidate());
3257 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003258 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003259 Candidate.Function = 0;
3260 Candidate.Surrogate = Conversion;
3261 Candidate.Viable = true;
3262 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003263 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003264 Candidate.Conversions.resize(NumArgs + 1);
3265
3266 // Determine the implicit conversion sequence for the implicit
3267 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003268 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003269 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003270 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003271 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003272 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003273 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003274 return;
3275 }
3276
3277 // The first conversion is actually a user-defined conversion whose
3278 // first conversion is ObjectInit's standard conversion (which is
3279 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003280 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003281 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003282 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003283 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003284 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003285 = Candidate.Conversions[0].UserDefined.Before;
3286 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3287
Mike Stump11289f42009-09-09 15:08:12 +00003288 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003289 unsigned NumArgsInProto = Proto->getNumArgs();
3290
3291 // (C++ 13.3.2p2): A candidate function having fewer than m
3292 // parameters is viable only if it has an ellipsis in its parameter
3293 // list (8.3.5).
3294 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3295 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003296 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003297 return;
3298 }
3299
3300 // Function types don't have any default arguments, so just check if
3301 // we have enough arguments.
3302 if (NumArgs < NumArgsInProto) {
3303 // Not enough arguments.
3304 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003305 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003306 return;
3307 }
3308
3309 // Determine the implicit conversion sequences for each of the
3310 // arguments.
3311 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3312 if (ArgIdx < NumArgsInProto) {
3313 // (C++ 13.3.2p3): for F to be a viable function, there shall
3314 // exist for each argument an implicit conversion sequence
3315 // (13.3.3.1) that converts that argument to the corresponding
3316 // parameter of F.
3317 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003318 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003319 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003320 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003321 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003322 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003323 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003324 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003325 break;
3326 }
3327 } else {
3328 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3329 // argument for which there is no corresponding parameter is
3330 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003331 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003332 }
3333 }
3334}
3335
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003336/// \brief Add overload candidates for overloaded operators that are
3337/// member functions.
3338///
3339/// Add the overloaded operator candidates that are member functions
3340/// for the operator Op that was used in an operator expression such
3341/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3342/// CandidateSet will store the added overload candidates. (C++
3343/// [over.match.oper]).
3344void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3345 SourceLocation OpLoc,
3346 Expr **Args, unsigned NumArgs,
3347 OverloadCandidateSet& CandidateSet,
3348 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003349 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3350
3351 // C++ [over.match.oper]p3:
3352 // For a unary operator @ with an operand of a type whose
3353 // cv-unqualified version is T1, and for a binary operator @ with
3354 // a left operand of a type whose cv-unqualified version is T1 and
3355 // a right operand of a type whose cv-unqualified version is T2,
3356 // three sets of candidate functions, designated member
3357 // candidates, non-member candidates and built-in candidates, are
3358 // constructed as follows:
3359 QualType T1 = Args[0]->getType();
3360 QualType T2;
3361 if (NumArgs > 1)
3362 T2 = Args[1]->getType();
3363
3364 // -- If T1 is a class type, the set of member candidates is the
3365 // result of the qualified lookup of T1::operator@
3366 // (13.3.1.1.1); otherwise, the set of member candidates is
3367 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003368 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003369 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003370 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003371 return;
Mike Stump11289f42009-09-09 15:08:12 +00003372
John McCall27b18f82009-11-17 02:14:36 +00003373 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3374 LookupQualifiedName(Operators, T1Rec->getDecl());
3375 Operators.suppressDiagnostics();
3376
Mike Stump11289f42009-09-09 15:08:12 +00003377 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003378 OperEnd = Operators.end();
3379 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003380 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003381 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003382 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003383 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003384 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003385}
3386
Douglas Gregora11693b2008-11-12 17:17:38 +00003387/// AddBuiltinCandidate - Add a candidate for a built-in
3388/// operator. ResultTy and ParamTys are the result and parameter types
3389/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003390/// arguments being passed to the candidate. IsAssignmentOperator
3391/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003392/// operator. NumContextualBoolArguments is the number of arguments
3393/// (at the beginning of the argument list) that will be contextually
3394/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003395void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003396 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003397 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003398 bool IsAssignmentOperator,
3399 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003400 // Overload resolution is always an unevaluated context.
3401 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3402
Douglas Gregora11693b2008-11-12 17:17:38 +00003403 // Add this candidate
3404 CandidateSet.push_back(OverloadCandidate());
3405 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003406 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003407 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003408 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003409 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003410 Candidate.BuiltinTypes.ResultTy = ResultTy;
3411 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3412 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3413
3414 // Determine the implicit conversion sequences for each of the
3415 // arguments.
3416 Candidate.Viable = true;
3417 Candidate.Conversions.resize(NumArgs);
3418 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003419 // C++ [over.match.oper]p4:
3420 // For the built-in assignment operators, conversions of the
3421 // left operand are restricted as follows:
3422 // -- no temporaries are introduced to hold the left operand, and
3423 // -- no user-defined conversions are applied to the left
3424 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003425 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003426 //
3427 // We block these conversions by turning off user-defined
3428 // conversions, since that is the only way that initialization of
3429 // a reference to a non-class type can occur from something that
3430 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003431 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003432 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003433 "Contextual conversion to bool requires bool type");
3434 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3435 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003436 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003437 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003438 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003439 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003440 }
John McCall0d1da222010-01-12 00:44:57 +00003441 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003442 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003443 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003444 break;
3445 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003446 }
3447}
3448
3449/// BuiltinCandidateTypeSet - A set of types that will be used for the
3450/// candidate operator functions for built-in operators (C++
3451/// [over.built]). The types are separated into pointer types and
3452/// enumeration types.
3453class BuiltinCandidateTypeSet {
3454 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003455 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003456
3457 /// PointerTypes - The set of pointer types that will be used in the
3458 /// built-in candidates.
3459 TypeSet PointerTypes;
3460
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003461 /// MemberPointerTypes - The set of member pointer types that will be
3462 /// used in the built-in candidates.
3463 TypeSet MemberPointerTypes;
3464
Douglas Gregora11693b2008-11-12 17:17:38 +00003465 /// EnumerationTypes - The set of enumeration types that will be
3466 /// used in the built-in candidates.
3467 TypeSet EnumerationTypes;
3468
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003469 /// Sema - The semantic analysis instance where we are building the
3470 /// candidate type set.
3471 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003472
Douglas Gregora11693b2008-11-12 17:17:38 +00003473 /// Context - The AST context in which we will build the type sets.
3474 ASTContext &Context;
3475
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003476 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3477 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003478 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003479
3480public:
3481 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003482 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003483
Mike Stump11289f42009-09-09 15:08:12 +00003484 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003485 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003486
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003487 void AddTypesConvertedFrom(QualType Ty,
3488 SourceLocation Loc,
3489 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003490 bool AllowExplicitConversions,
3491 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003492
3493 /// pointer_begin - First pointer type found;
3494 iterator pointer_begin() { return PointerTypes.begin(); }
3495
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003496 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003497 iterator pointer_end() { return PointerTypes.end(); }
3498
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003499 /// member_pointer_begin - First member pointer type found;
3500 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3501
3502 /// member_pointer_end - Past the last member pointer type found;
3503 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3504
Douglas Gregora11693b2008-11-12 17:17:38 +00003505 /// enumeration_begin - First enumeration type found;
3506 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3507
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003508 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003509 iterator enumeration_end() { return EnumerationTypes.end(); }
3510};
3511
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003512/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003513/// the set of pointer types along with any more-qualified variants of
3514/// that type. For example, if @p Ty is "int const *", this routine
3515/// will add "int const *", "int const volatile *", "int const
3516/// restrict *", and "int const volatile restrict *" to the set of
3517/// pointer types. Returns true if the add of @p Ty itself succeeded,
3518/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003519///
3520/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003521bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003522BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3523 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003524
Douglas Gregora11693b2008-11-12 17:17:38 +00003525 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003526 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003527 return false;
3528
John McCall8ccfcb52009-09-24 19:53:00 +00003529 const PointerType *PointerTy = Ty->getAs<PointerType>();
3530 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003531
John McCall8ccfcb52009-09-24 19:53:00 +00003532 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003533 // Don't add qualified variants of arrays. For one, they're not allowed
3534 // (the qualifier would sink to the element type), and for another, the
3535 // only overload situation where it matters is subscript or pointer +- int,
3536 // and those shouldn't have qualifier variants anyway.
3537 if (PointeeTy->isArrayType())
3538 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003539 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003540 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003541 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003542 bool hasVolatile = VisibleQuals.hasVolatile();
3543 bool hasRestrict = VisibleQuals.hasRestrict();
3544
John McCall8ccfcb52009-09-24 19:53:00 +00003545 // Iterate through all strict supersets of BaseCVR.
3546 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3547 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003548 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3549 // in the types.
3550 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3551 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003552 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3553 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003554 }
3555
3556 return true;
3557}
3558
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003559/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3560/// to the set of pointer types along with any more-qualified variants of
3561/// that type. For example, if @p Ty is "int const *", this routine
3562/// will add "int const *", "int const volatile *", "int const
3563/// restrict *", and "int const volatile restrict *" to the set of
3564/// pointer types. Returns true if the add of @p Ty itself succeeded,
3565/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003566///
3567/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003568bool
3569BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3570 QualType Ty) {
3571 // Insert this type.
3572 if (!MemberPointerTypes.insert(Ty))
3573 return false;
3574
John McCall8ccfcb52009-09-24 19:53:00 +00003575 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3576 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003577
John McCall8ccfcb52009-09-24 19:53:00 +00003578 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003579 // Don't add qualified variants of arrays. For one, they're not allowed
3580 // (the qualifier would sink to the element type), and for another, the
3581 // only overload situation where it matters is subscript or pointer +- int,
3582 // and those shouldn't have qualifier variants anyway.
3583 if (PointeeTy->isArrayType())
3584 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003585 const Type *ClassTy = PointerTy->getClass();
3586
3587 // Iterate through all strict supersets of the pointee type's CVR
3588 // qualifiers.
3589 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3590 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3591 if ((CVR | BaseCVR) != CVR) continue;
3592
3593 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3594 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003595 }
3596
3597 return true;
3598}
3599
Douglas Gregora11693b2008-11-12 17:17:38 +00003600/// AddTypesConvertedFrom - Add each of the types to which the type @p
3601/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003602/// primarily interested in pointer types and enumeration types. We also
3603/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003604/// AllowUserConversions is true if we should look at the conversion
3605/// functions of a class type, and AllowExplicitConversions if we
3606/// should also include the explicit conversion functions of a class
3607/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003608void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003609BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003610 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003611 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003612 bool AllowExplicitConversions,
3613 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003614 // Only deal with canonical types.
3615 Ty = Context.getCanonicalType(Ty);
3616
3617 // Look through reference types; they aren't part of the type of an
3618 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003619 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003620 Ty = RefTy->getPointeeType();
3621
3622 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003623 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003624
Sebastian Redl65ae2002009-11-05 16:36:20 +00003625 // If we're dealing with an array type, decay to the pointer.
3626 if (Ty->isArrayType())
3627 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3628
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003629 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003630 QualType PointeeTy = PointerTy->getPointeeType();
3631
3632 // Insert our type, and its more-qualified variants, into the set
3633 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003634 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003635 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003636 } else if (Ty->isMemberPointerType()) {
3637 // Member pointers are far easier, since the pointee can't be converted.
3638 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3639 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003640 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003641 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003642 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003643 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003644 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003645 // No conversion functions in incomplete types.
3646 return;
3647 }
Mike Stump11289f42009-09-09 15:08:12 +00003648
Douglas Gregora11693b2008-11-12 17:17:38 +00003649 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003650 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003651 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003652 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003653 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003654 NamedDecl *D = I.getDecl();
3655 if (isa<UsingShadowDecl>(D))
3656 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003657
Mike Stump11289f42009-09-09 15:08:12 +00003658 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003659 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003660 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003661 continue;
3662
John McCallda4458e2010-03-31 01:36:47 +00003663 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003664 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003665 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003666 VisibleQuals);
3667 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003668 }
3669 }
3670 }
3671}
3672
Douglas Gregor84605ae2009-08-24 13:43:27 +00003673/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3674/// the volatile- and non-volatile-qualified assignment operators for the
3675/// given type to the candidate set.
3676static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3677 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003678 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003679 unsigned NumArgs,
3680 OverloadCandidateSet &CandidateSet) {
3681 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003682
Douglas Gregor84605ae2009-08-24 13:43:27 +00003683 // T& operator=(T&, T)
3684 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3685 ParamTypes[1] = T;
3686 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3687 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003688
Douglas Gregor84605ae2009-08-24 13:43:27 +00003689 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3690 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003691 ParamTypes[0]
3692 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003693 ParamTypes[1] = T;
3694 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003695 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003696 }
3697}
Mike Stump11289f42009-09-09 15:08:12 +00003698
Sebastian Redl1054fae2009-10-25 17:03:50 +00003699/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3700/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003701static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3702 Qualifiers VRQuals;
3703 const RecordType *TyRec;
3704 if (const MemberPointerType *RHSMPType =
3705 ArgExpr->getType()->getAs<MemberPointerType>())
3706 TyRec = cast<RecordType>(RHSMPType->getClass());
3707 else
3708 TyRec = ArgExpr->getType()->getAs<RecordType>();
3709 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003710 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003711 VRQuals.addVolatile();
3712 VRQuals.addRestrict();
3713 return VRQuals;
3714 }
3715
3716 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003717 if (!ClassDecl->hasDefinition())
3718 return VRQuals;
3719
John McCallad371252010-01-20 00:46:10 +00003720 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003721 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003722
John McCallad371252010-01-20 00:46:10 +00003723 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003724 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003725 NamedDecl *D = I.getDecl();
3726 if (isa<UsingShadowDecl>(D))
3727 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3728 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003729 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3730 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3731 CanTy = ResTypeRef->getPointeeType();
3732 // Need to go down the pointer/mempointer chain and add qualifiers
3733 // as see them.
3734 bool done = false;
3735 while (!done) {
3736 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3737 CanTy = ResTypePtr->getPointeeType();
3738 else if (const MemberPointerType *ResTypeMPtr =
3739 CanTy->getAs<MemberPointerType>())
3740 CanTy = ResTypeMPtr->getPointeeType();
3741 else
3742 done = true;
3743 if (CanTy.isVolatileQualified())
3744 VRQuals.addVolatile();
3745 if (CanTy.isRestrictQualified())
3746 VRQuals.addRestrict();
3747 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3748 return VRQuals;
3749 }
3750 }
3751 }
3752 return VRQuals;
3753}
3754
Douglas Gregord08452f2008-11-19 15:42:04 +00003755/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3756/// operator overloads to the candidate set (C++ [over.built]), based
3757/// on the operator @p Op and the arguments given. For example, if the
3758/// operator is a binary '+', this routine might add "int
3759/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003760void
Mike Stump11289f42009-09-09 15:08:12 +00003761Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003762 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003763 Expr **Args, unsigned NumArgs,
3764 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003765 // The set of "promoted arithmetic types", which are the arithmetic
3766 // types are that preserved by promotion (C++ [over.built]p2). Note
3767 // that the first few of these types are the promoted integral
3768 // types; these types need to be first.
3769 // FIXME: What about complex?
3770 const unsigned FirstIntegralType = 0;
3771 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003772 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003773 LastPromotedIntegralType = 13;
3774 const unsigned FirstPromotedArithmeticType = 7,
3775 LastPromotedArithmeticType = 16;
3776 const unsigned NumArithmeticTypes = 16;
3777 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003778 Context.BoolTy, Context.CharTy, Context.WCharTy,
3779// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003780 Context.SignedCharTy, Context.ShortTy,
3781 Context.UnsignedCharTy, Context.UnsignedShortTy,
3782 Context.IntTy, Context.LongTy, Context.LongLongTy,
3783 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3784 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3785 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003786 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3787 "Invalid first promoted integral type");
3788 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3789 == Context.UnsignedLongLongTy &&
3790 "Invalid last promoted integral type");
3791 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3792 "Invalid first promoted arithmetic type");
3793 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3794 == Context.LongDoubleTy &&
3795 "Invalid last promoted arithmetic type");
3796
Douglas Gregora11693b2008-11-12 17:17:38 +00003797 // Find all of the types that the arguments can convert to, but only
3798 // if the operator we're looking at has built-in operator candidates
3799 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003800 Qualifiers VisibleTypeConversionsQuals;
3801 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003802 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3803 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3804
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003805 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003806 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3807 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003808 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003809 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003810 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003811 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003812 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003813 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003814 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003815 true,
3816 (Op == OO_Exclaim ||
3817 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003818 Op == OO_PipePipe),
3819 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003820 }
3821
3822 bool isComparison = false;
3823 switch (Op) {
3824 case OO_None:
3825 case NUM_OVERLOADED_OPERATORS:
3826 assert(false && "Expected an overloaded operator");
3827 break;
3828
Douglas Gregord08452f2008-11-19 15:42:04 +00003829 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003830 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003831 goto UnaryStar;
3832 else
3833 goto BinaryStar;
3834 break;
3835
3836 case OO_Plus: // '+' is either unary or binary
3837 if (NumArgs == 1)
3838 goto UnaryPlus;
3839 else
3840 goto BinaryPlus;
3841 break;
3842
3843 case OO_Minus: // '-' is either unary or binary
3844 if (NumArgs == 1)
3845 goto UnaryMinus;
3846 else
3847 goto BinaryMinus;
3848 break;
3849
3850 case OO_Amp: // '&' is either unary or binary
3851 if (NumArgs == 1)
3852 goto UnaryAmp;
3853 else
3854 goto BinaryAmp;
3855
3856 case OO_PlusPlus:
3857 case OO_MinusMinus:
3858 // C++ [over.built]p3:
3859 //
3860 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3861 // is either volatile or empty, there exist candidate operator
3862 // functions of the form
3863 //
3864 // VQ T& operator++(VQ T&);
3865 // T operator++(VQ T&, int);
3866 //
3867 // C++ [over.built]p4:
3868 //
3869 // For every pair (T, VQ), where T is an arithmetic type other
3870 // than bool, and VQ is either volatile or empty, there exist
3871 // candidate operator functions of the form
3872 //
3873 // VQ T& operator--(VQ T&);
3874 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003875 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003876 Arith < NumArithmeticTypes; ++Arith) {
3877 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003878 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003879 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003880
3881 // Non-volatile version.
3882 if (NumArgs == 1)
3883 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3884 else
3885 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003886 // heuristic to reduce number of builtin candidates in the set.
3887 // Add volatile version only if there are conversions to a volatile type.
3888 if (VisibleTypeConversionsQuals.hasVolatile()) {
3889 // Volatile version
3890 ParamTypes[0]
3891 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3892 if (NumArgs == 1)
3893 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3894 else
3895 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3896 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003897 }
3898
3899 // C++ [over.built]p5:
3900 //
3901 // For every pair (T, VQ), where T is a cv-qualified or
3902 // cv-unqualified object type, and VQ is either volatile or
3903 // empty, there exist candidate operator functions of the form
3904 //
3905 // T*VQ& operator++(T*VQ&);
3906 // T*VQ& operator--(T*VQ&);
3907 // T* operator++(T*VQ&, int);
3908 // T* operator--(T*VQ&, int);
3909 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3910 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3911 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003912 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003913 continue;
3914
Mike Stump11289f42009-09-09 15:08:12 +00003915 QualType ParamTypes[2] = {
3916 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003917 };
Mike Stump11289f42009-09-09 15:08:12 +00003918
Douglas Gregord08452f2008-11-19 15:42:04 +00003919 // Without volatile
3920 if (NumArgs == 1)
3921 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3922 else
3923 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3924
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003925 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3926 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003927 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003928 ParamTypes[0]
3929 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003930 if (NumArgs == 1)
3931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3932 else
3933 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3934 }
3935 }
3936 break;
3937
3938 UnaryStar:
3939 // C++ [over.built]p6:
3940 // For every cv-qualified or cv-unqualified object type T, there
3941 // exist candidate operator functions of the form
3942 //
3943 // T& operator*(T*);
3944 //
3945 // C++ [over.built]p7:
3946 // For every function type T, there exist candidate operator
3947 // functions of the form
3948 // T& operator*(T*);
3949 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3950 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3951 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003952 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003953 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003954 &ParamTy, Args, 1, CandidateSet);
3955 }
3956 break;
3957
3958 UnaryPlus:
3959 // C++ [over.built]p8:
3960 // For every type T, there exist candidate operator functions of
3961 // the form
3962 //
3963 // T* operator+(T*);
3964 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3965 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3966 QualType ParamTy = *Ptr;
3967 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3968 }
Mike Stump11289f42009-09-09 15:08:12 +00003969
Douglas Gregord08452f2008-11-19 15:42:04 +00003970 // Fall through
3971
3972 UnaryMinus:
3973 // C++ [over.built]p9:
3974 // For every promoted arithmetic type T, there exist candidate
3975 // operator functions of the form
3976 //
3977 // T operator+(T);
3978 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003979 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003980 Arith < LastPromotedArithmeticType; ++Arith) {
3981 QualType ArithTy = ArithmeticTypes[Arith];
3982 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3983 }
3984 break;
3985
3986 case OO_Tilde:
3987 // C++ [over.built]p10:
3988 // For every promoted integral type T, there exist candidate
3989 // operator functions of the form
3990 //
3991 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003992 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003993 Int < LastPromotedIntegralType; ++Int) {
3994 QualType IntTy = ArithmeticTypes[Int];
3995 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3996 }
3997 break;
3998
Douglas Gregora11693b2008-11-12 17:17:38 +00003999 case OO_New:
4000 case OO_Delete:
4001 case OO_Array_New:
4002 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004003 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004004 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004005 break;
4006
4007 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004008 UnaryAmp:
4009 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004010 // C++ [over.match.oper]p3:
4011 // -- For the operator ',', the unary operator '&', or the
4012 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004013 break;
4014
Douglas Gregor84605ae2009-08-24 13:43:27 +00004015 case OO_EqualEqual:
4016 case OO_ExclaimEqual:
4017 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004018 // For every pointer to member type T, there exist candidate operator
4019 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004020 //
4021 // bool operator==(T,T);
4022 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004023 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004024 MemPtr = CandidateTypes.member_pointer_begin(),
4025 MemPtrEnd = CandidateTypes.member_pointer_end();
4026 MemPtr != MemPtrEnd;
4027 ++MemPtr) {
4028 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4029 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4030 }
Mike Stump11289f42009-09-09 15:08:12 +00004031
Douglas Gregor84605ae2009-08-24 13:43:27 +00004032 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004033
Douglas Gregora11693b2008-11-12 17:17:38 +00004034 case OO_Less:
4035 case OO_Greater:
4036 case OO_LessEqual:
4037 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004038 // C++ [over.built]p15:
4039 //
4040 // For every pointer or enumeration type T, there exist
4041 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004042 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004043 // bool operator<(T, T);
4044 // bool operator>(T, T);
4045 // bool operator<=(T, T);
4046 // bool operator>=(T, T);
4047 // bool operator==(T, T);
4048 // bool operator!=(T, T);
4049 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4050 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4051 QualType ParamTypes[2] = { *Ptr, *Ptr };
4052 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4053 }
Mike Stump11289f42009-09-09 15:08:12 +00004054 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004055 = CandidateTypes.enumeration_begin();
4056 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4057 QualType ParamTypes[2] = { *Enum, *Enum };
4058 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4059 }
4060
4061 // Fall through.
4062 isComparison = true;
4063
Douglas Gregord08452f2008-11-19 15:42:04 +00004064 BinaryPlus:
4065 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004066 if (!isComparison) {
4067 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4068
4069 // C++ [over.built]p13:
4070 //
4071 // For every cv-qualified or cv-unqualified object type T
4072 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004073 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004074 // T* operator+(T*, ptrdiff_t);
4075 // T& operator[](T*, ptrdiff_t); [BELOW]
4076 // T* operator-(T*, ptrdiff_t);
4077 // T* operator+(ptrdiff_t, T*);
4078 // T& operator[](ptrdiff_t, T*); [BELOW]
4079 //
4080 // C++ [over.built]p14:
4081 //
4082 // For every T, where T is a pointer to object type, there
4083 // exist candidate operator functions of the form
4084 //
4085 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004086 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004087 = CandidateTypes.pointer_begin();
4088 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4089 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4090
4091 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4092 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4093
4094 if (Op == OO_Plus) {
4095 // T* operator+(ptrdiff_t, T*);
4096 ParamTypes[0] = ParamTypes[1];
4097 ParamTypes[1] = *Ptr;
4098 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4099 } else {
4100 // ptrdiff_t operator-(T, T);
4101 ParamTypes[1] = *Ptr;
4102 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4103 Args, 2, CandidateSet);
4104 }
4105 }
4106 }
4107 // Fall through
4108
Douglas Gregora11693b2008-11-12 17:17:38 +00004109 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004110 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004111 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004112 // C++ [over.built]p12:
4113 //
4114 // For every pair of promoted arithmetic types L and R, there
4115 // exist candidate operator functions of the form
4116 //
4117 // LR operator*(L, R);
4118 // LR operator/(L, R);
4119 // LR operator+(L, R);
4120 // LR operator-(L, R);
4121 // bool operator<(L, R);
4122 // bool operator>(L, R);
4123 // bool operator<=(L, R);
4124 // bool operator>=(L, R);
4125 // bool operator==(L, R);
4126 // bool operator!=(L, R);
4127 //
4128 // where LR is the result of the usual arithmetic conversions
4129 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004130 //
4131 // C++ [over.built]p24:
4132 //
4133 // For every pair of promoted arithmetic types L and R, there exist
4134 // candidate operator functions of the form
4135 //
4136 // LR operator?(bool, L, R);
4137 //
4138 // where LR is the result of the usual arithmetic conversions
4139 // between types L and R.
4140 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004141 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004142 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004143 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004144 Right < LastPromotedArithmeticType; ++Right) {
4145 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004146 QualType Result
4147 = isComparison
4148 ? Context.BoolTy
4149 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004150 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4151 }
4152 }
4153 break;
4154
4155 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004156 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004157 case OO_Caret:
4158 case OO_Pipe:
4159 case OO_LessLess:
4160 case OO_GreaterGreater:
4161 // C++ [over.built]p17:
4162 //
4163 // For every pair of promoted integral types L and R, there
4164 // exist candidate operator functions of the form
4165 //
4166 // LR operator%(L, R);
4167 // LR operator&(L, R);
4168 // LR operator^(L, R);
4169 // LR operator|(L, R);
4170 // L operator<<(L, R);
4171 // L operator>>(L, R);
4172 //
4173 // where LR is the result of the usual arithmetic conversions
4174 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004175 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004176 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004177 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004178 Right < LastPromotedIntegralType; ++Right) {
4179 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4180 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4181 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004182 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004183 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4184 }
4185 }
4186 break;
4187
4188 case OO_Equal:
4189 // C++ [over.built]p20:
4190 //
4191 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004192 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004193 // empty, there exist candidate operator functions of the form
4194 //
4195 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004196 for (BuiltinCandidateTypeSet::iterator
4197 Enum = CandidateTypes.enumeration_begin(),
4198 EnumEnd = CandidateTypes.enumeration_end();
4199 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004200 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004201 CandidateSet);
4202 for (BuiltinCandidateTypeSet::iterator
4203 MemPtr = CandidateTypes.member_pointer_begin(),
4204 MemPtrEnd = CandidateTypes.member_pointer_end();
4205 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004206 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004207 CandidateSet);
4208 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004209
4210 case OO_PlusEqual:
4211 case OO_MinusEqual:
4212 // C++ [over.built]p19:
4213 //
4214 // For every pair (T, VQ), where T is any type and VQ is either
4215 // volatile or empty, there exist candidate operator functions
4216 // of the form
4217 //
4218 // T*VQ& operator=(T*VQ&, T*);
4219 //
4220 // C++ [over.built]p21:
4221 //
4222 // For every pair (T, VQ), where T is a cv-qualified or
4223 // cv-unqualified object type and VQ is either volatile or
4224 // empty, there exist candidate operator functions of the form
4225 //
4226 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4227 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4228 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4229 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4230 QualType ParamTypes[2];
4231 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4232
4233 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004234 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004235 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4236 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004237
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004238 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4239 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004240 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004241 ParamTypes[0]
4242 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004243 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4244 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004245 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004246 }
4247 // Fall through.
4248
4249 case OO_StarEqual:
4250 case OO_SlashEqual:
4251 // C++ [over.built]p18:
4252 //
4253 // For every triple (L, VQ, R), where L is an arithmetic type,
4254 // VQ is either volatile or empty, and R is a promoted
4255 // arithmetic type, there exist candidate operator functions of
4256 // the form
4257 //
4258 // VQ L& operator=(VQ L&, R);
4259 // VQ L& operator*=(VQ L&, R);
4260 // VQ L& operator/=(VQ L&, R);
4261 // VQ L& operator+=(VQ L&, R);
4262 // VQ L& operator-=(VQ L&, R);
4263 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004264 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004265 Right < LastPromotedArithmeticType; ++Right) {
4266 QualType ParamTypes[2];
4267 ParamTypes[1] = ArithmeticTypes[Right];
4268
4269 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004270 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004271 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4272 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004273
4274 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004275 if (VisibleTypeConversionsQuals.hasVolatile()) {
4276 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4277 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4278 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4279 /*IsAssigmentOperator=*/Op == OO_Equal);
4280 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004281 }
4282 }
4283 break;
4284
4285 case OO_PercentEqual:
4286 case OO_LessLessEqual:
4287 case OO_GreaterGreaterEqual:
4288 case OO_AmpEqual:
4289 case OO_CaretEqual:
4290 case OO_PipeEqual:
4291 // C++ [over.built]p22:
4292 //
4293 // For every triple (L, VQ, R), where L is an integral type, VQ
4294 // is either volatile or empty, and R is a promoted integral
4295 // type, there exist candidate operator functions of the form
4296 //
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 // VQ L& operator^=(VQ L&, R);
4302 // VQ L& operator|=(VQ L&, R);
4303 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004304 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004305 Right < LastPromotedIntegralType; ++Right) {
4306 QualType ParamTypes[2];
4307 ParamTypes[1] = ArithmeticTypes[Right];
4308
4309 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004310 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004311 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004312 if (VisibleTypeConversionsQuals.hasVolatile()) {
4313 // Add this built-in operator as a candidate (VQ is 'volatile').
4314 ParamTypes[0] = ArithmeticTypes[Left];
4315 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4316 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4317 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4318 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004319 }
4320 }
4321 break;
4322
Douglas Gregord08452f2008-11-19 15:42:04 +00004323 case OO_Exclaim: {
4324 // C++ [over.operator]p23:
4325 //
4326 // There also exist candidate operator functions of the form
4327 //
Mike Stump11289f42009-09-09 15:08:12 +00004328 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004329 // bool operator&&(bool, bool); [BELOW]
4330 // bool operator||(bool, bool); [BELOW]
4331 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004332 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4333 /*IsAssignmentOperator=*/false,
4334 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004335 break;
4336 }
4337
Douglas Gregora11693b2008-11-12 17:17:38 +00004338 case OO_AmpAmp:
4339 case OO_PipePipe: {
4340 // C++ [over.operator]p23:
4341 //
4342 // There also exist candidate operator functions of the form
4343 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004344 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004345 // bool operator&&(bool, bool);
4346 // bool operator||(bool, bool);
4347 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004348 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4349 /*IsAssignmentOperator=*/false,
4350 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004351 break;
4352 }
4353
4354 case OO_Subscript:
4355 // C++ [over.built]p13:
4356 //
4357 // For every cv-qualified or cv-unqualified object type T there
4358 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004359 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004360 // T* operator+(T*, ptrdiff_t); [ABOVE]
4361 // T& operator[](T*, ptrdiff_t);
4362 // T* operator-(T*, ptrdiff_t); [ABOVE]
4363 // T* operator+(ptrdiff_t, T*); [ABOVE]
4364 // T& operator[](ptrdiff_t, T*);
4365 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4366 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4367 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004368 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004369 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004370
4371 // T& operator[](T*, ptrdiff_t)
4372 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4373
4374 // T& operator[](ptrdiff_t, T*);
4375 ParamTypes[0] = ParamTypes[1];
4376 ParamTypes[1] = *Ptr;
4377 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4378 }
4379 break;
4380
4381 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004382 // C++ [over.built]p11:
4383 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4384 // C1 is the same type as C2 or is a derived class of C2, T is an object
4385 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4386 // there exist candidate operator functions of the form
4387 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4388 // where CV12 is the union of CV1 and CV2.
4389 {
4390 for (BuiltinCandidateTypeSet::iterator Ptr =
4391 CandidateTypes.pointer_begin();
4392 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4393 QualType C1Ty = (*Ptr);
4394 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004395 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004396 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004397 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004398 if (!isa<RecordType>(C1))
4399 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004400 // heuristic to reduce number of builtin candidates in the set.
4401 // Add volatile/restrict version only if there are conversions to a
4402 // volatile/restrict type.
4403 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4404 continue;
4405 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4406 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004407 }
4408 for (BuiltinCandidateTypeSet::iterator
4409 MemPtr = CandidateTypes.member_pointer_begin(),
4410 MemPtrEnd = CandidateTypes.member_pointer_end();
4411 MemPtr != MemPtrEnd; ++MemPtr) {
4412 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4413 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004414 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004415 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4416 break;
4417 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4418 // build CV12 T&
4419 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004420 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4421 T.isVolatileQualified())
4422 continue;
4423 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4424 T.isRestrictQualified())
4425 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004426 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004427 QualType ResultTy = Context.getLValueReferenceType(T);
4428 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4429 }
4430 }
4431 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004432 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004433
4434 case OO_Conditional:
4435 // Note that we don't consider the first argument, since it has been
4436 // contextually converted to bool long ago. The candidates below are
4437 // therefore added as binary.
4438 //
4439 // C++ [over.built]p24:
4440 // For every type T, where T is a pointer or pointer-to-member type,
4441 // there exist candidate operator functions of the form
4442 //
4443 // T operator?(bool, T, T);
4444 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004445 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4446 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4447 QualType ParamTypes[2] = { *Ptr, *Ptr };
4448 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4449 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004450 for (BuiltinCandidateTypeSet::iterator Ptr =
4451 CandidateTypes.member_pointer_begin(),
4452 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4453 QualType ParamTypes[2] = { *Ptr, *Ptr };
4454 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4455 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004456 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004457 }
4458}
4459
Douglas Gregore254f902009-02-04 00:32:51 +00004460/// \brief Add function candidates found via argument-dependent lookup
4461/// to the set of overloading candidates.
4462///
4463/// This routine performs argument-dependent name lookup based on the
4464/// given function name (which may also be an operator name) and adds
4465/// all of the overload candidates found by ADL to the overload
4466/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004467void
Douglas Gregore254f902009-02-04 00:32:51 +00004468Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004469 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004470 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004471 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004472 OverloadCandidateSet& CandidateSet,
4473 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004474 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004475
John McCall91f61fc2010-01-26 06:04:06 +00004476 // FIXME: This approach for uniquing ADL results (and removing
4477 // redundant candidates from the set) relies on pointer-equality,
4478 // which means we need to key off the canonical decl. However,
4479 // always going back to the canonical decl might not get us the
4480 // right set of default arguments. What default arguments are
4481 // we supposed to consider on ADL candidates, anyway?
4482
Douglas Gregorcabea402009-09-22 15:41:20 +00004483 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004484 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004485
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004486 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004487 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4488 CandEnd = CandidateSet.end();
4489 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004490 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004491 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004492 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004493 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004494 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004495
4496 // For each of the ADL candidates we found, add it to the overload
4497 // set.
John McCall8fe68082010-01-26 07:16:45 +00004498 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004499 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004500 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004501 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004502 continue;
4503
John McCalla0296f72010-03-19 07:35:19 +00004504 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004505 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004506 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004507 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004508 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004509 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004510 }
Douglas Gregore254f902009-02-04 00:32:51 +00004511}
4512
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004513/// isBetterOverloadCandidate - Determines whether the first overload
4514/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004515bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004516Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004517 const OverloadCandidate& Cand2,
4518 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004519 // Define viable functions to be better candidates than non-viable
4520 // functions.
4521 if (!Cand2.Viable)
4522 return Cand1.Viable;
4523 else if (!Cand1.Viable)
4524 return false;
4525
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004526 // C++ [over.match.best]p1:
4527 //
4528 // -- if F is a static member function, ICS1(F) is defined such
4529 // that ICS1(F) is neither better nor worse than ICS1(G) for
4530 // any function G, and, symmetrically, ICS1(G) is neither
4531 // better nor worse than ICS1(F).
4532 unsigned StartArg = 0;
4533 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4534 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004535
Douglas Gregord3cb3562009-07-07 23:38:56 +00004536 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004537 // A viable function F1 is defined to be a better function than another
4538 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004539 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004540 unsigned NumArgs = Cand1.Conversions.size();
4541 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4542 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004543 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004544 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4545 Cand2.Conversions[ArgIdx])) {
4546 case ImplicitConversionSequence::Better:
4547 // Cand1 has a better conversion sequence.
4548 HasBetterConversion = true;
4549 break;
4550
4551 case ImplicitConversionSequence::Worse:
4552 // Cand1 can't be better than Cand2.
4553 return false;
4554
4555 case ImplicitConversionSequence::Indistinguishable:
4556 // Do nothing.
4557 break;
4558 }
4559 }
4560
Mike Stump11289f42009-09-09 15:08:12 +00004561 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004562 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004563 if (HasBetterConversion)
4564 return true;
4565
Mike Stump11289f42009-09-09 15:08:12 +00004566 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004567 // specialization, or, if not that,
4568 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4569 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4570 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004571
4572 // -- F1 and F2 are function template specializations, and the function
4573 // template for F1 is more specialized than the template for F2
4574 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004575 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004576 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4577 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004578 if (FunctionTemplateDecl *BetterTemplate
4579 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4580 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004581 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004582 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4583 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004584 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004585
Douglas Gregora1f013e2008-11-07 22:36:19 +00004586 // -- the context is an initialization by user-defined conversion
4587 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4588 // from the return type of F1 to the destination type (i.e.,
4589 // the type of the entity being initialized) is a better
4590 // conversion sequence than the standard conversion sequence
4591 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004592 if (Cand1.Function && Cand2.Function &&
4593 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004594 isa<CXXConversionDecl>(Cand2.Function)) {
4595 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4596 Cand2.FinalConversion)) {
4597 case ImplicitConversionSequence::Better:
4598 // Cand1 has a better conversion sequence.
4599 return true;
4600
4601 case ImplicitConversionSequence::Worse:
4602 // Cand1 can't be better than Cand2.
4603 return false;
4604
4605 case ImplicitConversionSequence::Indistinguishable:
4606 // Do nothing
4607 break;
4608 }
4609 }
4610
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004611 return false;
4612}
4613
Mike Stump11289f42009-09-09 15:08:12 +00004614/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004615/// within an overload candidate set.
4616///
4617/// \param CandidateSet the set of candidate functions.
4618///
4619/// \param Loc the location of the function name (or operator symbol) for
4620/// which overload resolution occurs.
4621///
Mike Stump11289f42009-09-09 15:08:12 +00004622/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004623/// function, Best points to the candidate function found.
4624///
4625/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004626OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4627 SourceLocation Loc,
4628 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004629 // Find the best viable function.
4630 Best = CandidateSet.end();
4631 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4632 Cand != CandidateSet.end(); ++Cand) {
4633 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004634 if (Best == CandidateSet.end() ||
4635 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004636 Best = Cand;
4637 }
4638 }
4639
4640 // If we didn't find any viable functions, abort.
4641 if (Best == CandidateSet.end())
4642 return OR_No_Viable_Function;
4643
4644 // Make sure that this function is better than every other viable
4645 // function. If not, we have an ambiguity.
4646 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4647 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004648 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004649 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004650 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004651 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004652 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004653 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004654 }
Mike Stump11289f42009-09-09 15:08:12 +00004655
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004656 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004657 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004658 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004659 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004660 return OR_Deleted;
4661
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004662 // C++ [basic.def.odr]p2:
4663 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004664 // when referred to from a potentially-evaluated expression. [Note: this
4665 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004666 // (clause 13), user-defined conversions (12.3.2), allocation function for
4667 // placement new (5.3.4), as well as non-default initialization (8.5).
4668 if (Best->Function)
4669 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004670 return OR_Success;
4671}
4672
John McCall53262c92010-01-12 02:15:36 +00004673namespace {
4674
4675enum OverloadCandidateKind {
4676 oc_function,
4677 oc_method,
4678 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004679 oc_function_template,
4680 oc_method_template,
4681 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004682 oc_implicit_default_constructor,
4683 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004684 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004685};
4686
John McCalle1ac8d12010-01-13 00:25:19 +00004687OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4688 FunctionDecl *Fn,
4689 std::string &Description) {
4690 bool isTemplate = false;
4691
4692 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4693 isTemplate = true;
4694 Description = S.getTemplateArgumentBindingsText(
4695 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4696 }
John McCallfd0b2f82010-01-06 09:43:14 +00004697
4698 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004699 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004700 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004701
John McCall53262c92010-01-12 02:15:36 +00004702 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4703 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004704 }
4705
4706 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4707 // This actually gets spelled 'candidate function' for now, but
4708 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004709 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004710 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004711
4712 assert(Meth->isCopyAssignment()
4713 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004714 return oc_implicit_copy_assignment;
4715 }
4716
John McCalle1ac8d12010-01-13 00:25:19 +00004717 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004718}
4719
4720} // end anonymous namespace
4721
4722// Notes the location of an overload candidate.
4723void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004724 std::string FnDesc;
4725 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4726 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4727 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004728}
4729
John McCall0d1da222010-01-12 00:44:57 +00004730/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4731/// "lead" diagnostic; it will be given two arguments, the source and
4732/// target types of the conversion.
4733void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4734 SourceLocation CaretLoc,
4735 const PartialDiagnostic &PDiag) {
4736 Diag(CaretLoc, PDiag)
4737 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4738 for (AmbiguousConversionSequence::const_iterator
4739 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4740 NoteOverloadCandidate(*I);
4741 }
John McCall12f97bc2010-01-08 04:41:39 +00004742}
4743
John McCall0d1da222010-01-12 00:44:57 +00004744namespace {
4745
John McCall6a61b522010-01-13 09:16:55 +00004746void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4747 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4748 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004749 assert(Cand->Function && "for now, candidate must be a function");
4750 FunctionDecl *Fn = Cand->Function;
4751
4752 // There's a conversion slot for the object argument if this is a
4753 // non-constructor method. Note that 'I' corresponds the
4754 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004755 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004756 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004757 if (I == 0)
4758 isObjectArgument = true;
4759 else
4760 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004761 }
4762
John McCalle1ac8d12010-01-13 00:25:19 +00004763 std::string FnDesc;
4764 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4765
John McCall6a61b522010-01-13 09:16:55 +00004766 Expr *FromExpr = Conv.Bad.FromExpr;
4767 QualType FromTy = Conv.Bad.getFromType();
4768 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004769
John McCallfb7ad0f2010-02-02 02:42:52 +00004770 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004771 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004772 Expr *E = FromExpr->IgnoreParens();
4773 if (isa<UnaryOperator>(E))
4774 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004775 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004776
4777 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4778 << (unsigned) FnKind << FnDesc
4779 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4780 << ToTy << Name << I+1;
4781 return;
4782 }
4783
John McCall6d174642010-01-23 08:10:49 +00004784 // Do some hand-waving analysis to see if the non-viability is due
4785 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004786 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4787 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4788 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4789 CToTy = RT->getPointeeType();
4790 else {
4791 // TODO: detect and diagnose the full richness of const mismatches.
4792 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4793 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4794 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4795 }
4796
4797 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4798 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4799 // It is dumb that we have to do this here.
4800 while (isa<ArrayType>(CFromTy))
4801 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4802 while (isa<ArrayType>(CToTy))
4803 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4804
4805 Qualifiers FromQs = CFromTy.getQualifiers();
4806 Qualifiers ToQs = CToTy.getQualifiers();
4807
4808 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4809 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4810 << (unsigned) FnKind << FnDesc
4811 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4812 << FromTy
4813 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4814 << (unsigned) isObjectArgument << I+1;
4815 return;
4816 }
4817
4818 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4819 assert(CVR && "unexpected qualifiers mismatch");
4820
4821 if (isObjectArgument) {
4822 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4823 << (unsigned) FnKind << FnDesc
4824 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4825 << FromTy << (CVR - 1);
4826 } else {
4827 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4828 << (unsigned) FnKind << FnDesc
4829 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4830 << FromTy << (CVR - 1) << I+1;
4831 }
4832 return;
4833 }
4834
John McCall6d174642010-01-23 08:10:49 +00004835 // Diagnose references or pointers to incomplete types differently,
4836 // since it's far from impossible that the incompleteness triggered
4837 // the failure.
4838 QualType TempFromTy = FromTy.getNonReferenceType();
4839 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4840 TempFromTy = PTy->getPointeeType();
4841 if (TempFromTy->isIncompleteType()) {
4842 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4843 << (unsigned) FnKind << FnDesc
4844 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4845 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4846 return;
4847 }
4848
John McCall47000992010-01-14 03:28:57 +00004849 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004850 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4851 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004852 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004853 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004854}
4855
4856void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4857 unsigned NumFormalArgs) {
4858 // TODO: treat calls to a missing default constructor as a special case
4859
4860 FunctionDecl *Fn = Cand->Function;
4861 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4862
4863 unsigned MinParams = Fn->getMinRequiredArguments();
4864
4865 // at least / at most / exactly
4866 unsigned mode, modeCount;
4867 if (NumFormalArgs < MinParams) {
4868 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4869 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4870 mode = 0; // "at least"
4871 else
4872 mode = 2; // "exactly"
4873 modeCount = MinParams;
4874 } else {
4875 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4876 if (MinParams != FnTy->getNumArgs())
4877 mode = 1; // "at most"
4878 else
4879 mode = 2; // "exactly"
4880 modeCount = FnTy->getNumArgs();
4881 }
4882
4883 std::string Description;
4884 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4885
4886 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4887 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004888}
4889
John McCall8b9ed552010-02-01 18:53:26 +00004890/// Diagnose a failed template-argument deduction.
4891void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4892 Expr **Args, unsigned NumArgs) {
4893 FunctionDecl *Fn = Cand->Function; // pattern
4894
4895 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4896 Cand->DeductionFailure.TemplateParameter);
4897
4898 switch (Cand->DeductionFailure.Result) {
4899 case Sema::TDK_Success:
4900 llvm_unreachable("TDK_success while diagnosing bad deduction");
4901
4902 case Sema::TDK_Incomplete: {
4903 NamedDecl *ParamD;
4904 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4905 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4906 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4907 assert(ParamD && "no parameter found for incomplete deduction result");
4908 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4909 << ParamD->getDeclName();
4910 return;
4911 }
4912
4913 // TODO: diagnose these individually, then kill off
4914 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4915 case Sema::TDK_InstantiationDepth:
4916 case Sema::TDK_Inconsistent:
4917 case Sema::TDK_InconsistentQuals:
4918 case Sema::TDK_SubstitutionFailure:
4919 case Sema::TDK_NonDeducedMismatch:
4920 case Sema::TDK_TooManyArguments:
4921 case Sema::TDK_TooFewArguments:
4922 case Sema::TDK_InvalidExplicitArguments:
4923 case Sema::TDK_FailedOverloadResolution:
4924 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4925 return;
4926 }
4927}
4928
4929/// Generates a 'note' diagnostic for an overload candidate. We've
4930/// already generated a primary error at the call site.
4931///
4932/// It really does need to be a single diagnostic with its caret
4933/// pointed at the candidate declaration. Yes, this creates some
4934/// major challenges of technical writing. Yes, this makes pointing
4935/// out problems with specific arguments quite awkward. It's still
4936/// better than generating twenty screens of text for every failed
4937/// overload.
4938///
4939/// It would be great to be able to express per-candidate problems
4940/// more richly for those diagnostic clients that cared, but we'd
4941/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004942void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4943 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004944 FunctionDecl *Fn = Cand->Function;
4945
John McCall12f97bc2010-01-08 04:41:39 +00004946 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004947 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004948 std::string FnDesc;
4949 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004950
4951 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004952 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004953 return;
John McCall12f97bc2010-01-08 04:41:39 +00004954 }
4955
John McCalle1ac8d12010-01-13 00:25:19 +00004956 // We don't really have anything else to say about viable candidates.
4957 if (Cand->Viable) {
4958 S.NoteOverloadCandidate(Fn);
4959 return;
4960 }
John McCall0d1da222010-01-12 00:44:57 +00004961
John McCall6a61b522010-01-13 09:16:55 +00004962 switch (Cand->FailureKind) {
4963 case ovl_fail_too_many_arguments:
4964 case ovl_fail_too_few_arguments:
4965 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004966
John McCall6a61b522010-01-13 09:16:55 +00004967 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004968 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4969
John McCallfe796dd2010-01-23 05:17:32 +00004970 case ovl_fail_trivial_conversion:
4971 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004972 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00004973 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004974
John McCall65eb8792010-02-25 01:37:24 +00004975 case ovl_fail_bad_conversion: {
4976 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4977 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00004978 if (Cand->Conversions[I].isBad())
4979 return DiagnoseBadConversion(S, Cand, I);
4980
4981 // FIXME: this currently happens when we're called from SemaInit
4982 // when user-conversion overload fails. Figure out how to handle
4983 // those conditions and diagnose them well.
4984 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004985 }
John McCall65eb8792010-02-25 01:37:24 +00004986 }
John McCalld3224162010-01-08 00:58:21 +00004987}
4988
4989void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4990 // Desugar the type of the surrogate down to a function type,
4991 // retaining as many typedefs as possible while still showing
4992 // the function type (and, therefore, its parameter types).
4993 QualType FnType = Cand->Surrogate->getConversionType();
4994 bool isLValueReference = false;
4995 bool isRValueReference = false;
4996 bool isPointer = false;
4997 if (const LValueReferenceType *FnTypeRef =
4998 FnType->getAs<LValueReferenceType>()) {
4999 FnType = FnTypeRef->getPointeeType();
5000 isLValueReference = true;
5001 } else if (const RValueReferenceType *FnTypeRef =
5002 FnType->getAs<RValueReferenceType>()) {
5003 FnType = FnTypeRef->getPointeeType();
5004 isRValueReference = true;
5005 }
5006 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5007 FnType = FnTypePtr->getPointeeType();
5008 isPointer = true;
5009 }
5010 // Desugar down to a function type.
5011 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5012 // Reconstruct the pointer/reference as appropriate.
5013 if (isPointer) FnType = S.Context.getPointerType(FnType);
5014 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5015 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5016
5017 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5018 << FnType;
5019}
5020
5021void NoteBuiltinOperatorCandidate(Sema &S,
5022 const char *Opc,
5023 SourceLocation OpLoc,
5024 OverloadCandidate *Cand) {
5025 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5026 std::string TypeStr("operator");
5027 TypeStr += Opc;
5028 TypeStr += "(";
5029 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5030 if (Cand->Conversions.size() == 1) {
5031 TypeStr += ")";
5032 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5033 } else {
5034 TypeStr += ", ";
5035 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5036 TypeStr += ")";
5037 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5038 }
5039}
5040
5041void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5042 OverloadCandidate *Cand) {
5043 unsigned NoOperands = Cand->Conversions.size();
5044 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5045 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005046 if (ICS.isBad()) break; // all meaningless after first invalid
5047 if (!ICS.isAmbiguous()) continue;
5048
5049 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005050 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005051 }
5052}
5053
John McCall3712d9e2010-01-15 23:32:50 +00005054SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5055 if (Cand->Function)
5056 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005057 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005058 return Cand->Surrogate->getLocation();
5059 return SourceLocation();
5060}
5061
John McCallad2587a2010-01-12 00:48:53 +00005062struct CompareOverloadCandidatesForDisplay {
5063 Sema &S;
5064 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005065
5066 bool operator()(const OverloadCandidate *L,
5067 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005068 // Fast-path this check.
5069 if (L == R) return false;
5070
John McCall12f97bc2010-01-08 04:41:39 +00005071 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005072 if (L->Viable) {
5073 if (!R->Viable) return true;
5074
5075 // TODO: introduce a tri-valued comparison for overload
5076 // candidates. Would be more worthwhile if we had a sort
5077 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005078 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5079 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005080 } else if (R->Viable)
5081 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005082
John McCall3712d9e2010-01-15 23:32:50 +00005083 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005084
John McCall3712d9e2010-01-15 23:32:50 +00005085 // Criteria by which we can sort non-viable candidates:
5086 if (!L->Viable) {
5087 // 1. Arity mismatches come after other candidates.
5088 if (L->FailureKind == ovl_fail_too_many_arguments ||
5089 L->FailureKind == ovl_fail_too_few_arguments)
5090 return false;
5091 if (R->FailureKind == ovl_fail_too_many_arguments ||
5092 R->FailureKind == ovl_fail_too_few_arguments)
5093 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005094
John McCallfe796dd2010-01-23 05:17:32 +00005095 // 2. Bad conversions come first and are ordered by the number
5096 // of bad conversions and quality of good conversions.
5097 if (L->FailureKind == ovl_fail_bad_conversion) {
5098 if (R->FailureKind != ovl_fail_bad_conversion)
5099 return true;
5100
5101 // If there's any ordering between the defined conversions...
5102 // FIXME: this might not be transitive.
5103 assert(L->Conversions.size() == R->Conversions.size());
5104
5105 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005106 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5107 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005108 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5109 R->Conversions[I])) {
5110 case ImplicitConversionSequence::Better:
5111 leftBetter++;
5112 break;
5113
5114 case ImplicitConversionSequence::Worse:
5115 leftBetter--;
5116 break;
5117
5118 case ImplicitConversionSequence::Indistinguishable:
5119 break;
5120 }
5121 }
5122 if (leftBetter > 0) return true;
5123 if (leftBetter < 0) return false;
5124
5125 } else if (R->FailureKind == ovl_fail_bad_conversion)
5126 return false;
5127
John McCall3712d9e2010-01-15 23:32:50 +00005128 // TODO: others?
5129 }
5130
5131 // Sort everything else by location.
5132 SourceLocation LLoc = GetLocationForCandidate(L);
5133 SourceLocation RLoc = GetLocationForCandidate(R);
5134
5135 // Put candidates without locations (e.g. builtins) at the end.
5136 if (LLoc.isInvalid()) return false;
5137 if (RLoc.isInvalid()) return true;
5138
5139 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005140 }
5141};
5142
John McCallfe796dd2010-01-23 05:17:32 +00005143/// CompleteNonViableCandidate - Normally, overload resolution only
5144/// computes up to the first
5145void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5146 Expr **Args, unsigned NumArgs) {
5147 assert(!Cand->Viable);
5148
5149 // Don't do anything on failures other than bad conversion.
5150 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5151
5152 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005153 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005154 unsigned ConvCount = Cand->Conversions.size();
5155 while (true) {
5156 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5157 ConvIdx++;
5158 if (Cand->Conversions[ConvIdx - 1].isBad())
5159 break;
5160 }
5161
5162 if (ConvIdx == ConvCount)
5163 return;
5164
John McCall65eb8792010-02-25 01:37:24 +00005165 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5166 "remaining conversion is initialized?");
5167
Douglas Gregoradc7a702010-04-16 17:45:54 +00005168 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005169 // operation somehow.
5170 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005171
5172 const FunctionProtoType* Proto;
5173 unsigned ArgIdx = ConvIdx;
5174
5175 if (Cand->IsSurrogate) {
5176 QualType ConvType
5177 = Cand->Surrogate->getConversionType().getNonReferenceType();
5178 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5179 ConvType = ConvPtrType->getPointeeType();
5180 Proto = ConvType->getAs<FunctionProtoType>();
5181 ArgIdx--;
5182 } else if (Cand->Function) {
5183 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5184 if (isa<CXXMethodDecl>(Cand->Function) &&
5185 !isa<CXXConstructorDecl>(Cand->Function))
5186 ArgIdx--;
5187 } else {
5188 // Builtin binary operator with a bad first conversion.
5189 assert(ConvCount <= 3);
5190 for (; ConvIdx != ConvCount; ++ConvIdx)
5191 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005192 = TryCopyInitialization(S, Args[ConvIdx],
5193 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5194 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005195 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005196 return;
5197 }
5198
5199 // Fill in the rest of the conversions.
5200 unsigned NumArgsInProto = Proto->getNumArgs();
5201 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5202 if (ArgIdx < NumArgsInProto)
5203 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005204 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5205 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005206 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005207 else
5208 Cand->Conversions[ConvIdx].setEllipsis();
5209 }
5210}
5211
John McCalld3224162010-01-08 00:58:21 +00005212} // end anonymous namespace
5213
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005214/// PrintOverloadCandidates - When overload resolution fails, prints
5215/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005216/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005217void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005218Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005219 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005220 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005221 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005222 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005223 // Sort the candidates by viability and position. Sorting directly would
5224 // be prohibitive, so we make a set of pointers and sort those.
5225 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5226 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5227 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5228 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005229 Cand != LastCand; ++Cand) {
5230 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005231 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005232 else if (OCD == OCD_AllCandidates) {
5233 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5234 Cands.push_back(Cand);
5235 }
5236 }
5237
John McCallad2587a2010-01-12 00:48:53 +00005238 std::sort(Cands.begin(), Cands.end(),
5239 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005240
John McCall0d1da222010-01-12 00:44:57 +00005241 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005242
John McCall12f97bc2010-01-08 04:41:39 +00005243 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5244 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5245 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005246
John McCalld3224162010-01-08 00:58:21 +00005247 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005248 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005249 else if (Cand->IsSurrogate)
5250 NoteSurrogateCandidate(*this, Cand);
5251
5252 // This a builtin candidate. We do not, in general, want to list
5253 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005254 else if (Cand->Viable) {
5255 // Generally we only see ambiguities including viable builtin
5256 // operators if overload resolution got screwed up by an
5257 // ambiguous user-defined conversion.
5258 //
5259 // FIXME: It's quite possible for different conversions to see
5260 // different ambiguities, though.
5261 if (!ReportedAmbiguousConversions) {
5262 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5263 ReportedAmbiguousConversions = true;
5264 }
John McCalld3224162010-01-08 00:58:21 +00005265
John McCall0d1da222010-01-12 00:44:57 +00005266 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005267 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005268 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005269 }
5270}
5271
John McCalla0296f72010-03-19 07:35:19 +00005272static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005273 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005274 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005275
John McCalla0296f72010-03-19 07:35:19 +00005276 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005277}
5278
Douglas Gregorcd695e52008-11-10 20:40:00 +00005279/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5280/// an overloaded function (C++ [over.over]), where @p From is an
5281/// expression with overloaded function type and @p ToType is the type
5282/// we're trying to resolve to. For example:
5283///
5284/// @code
5285/// int f(double);
5286/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005287///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005288/// int (*pfd)(double) = f; // selects f(double)
5289/// @endcode
5290///
5291/// This routine returns the resulting FunctionDecl if it could be
5292/// resolved, and NULL otherwise. When @p Complain is true, this
5293/// routine will emit diagnostics if there is an error.
5294FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005295Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005296 bool Complain,
5297 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005298 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005299 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005300 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005301 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005302 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005303 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005304 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005305 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005306 FunctionType = MemTypePtr->getPointeeType();
5307 IsMember = true;
5308 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005309
Douglas Gregorcd695e52008-11-10 20:40:00 +00005310 // C++ [over.over]p1:
5311 // [...] [Note: any redundant set of parentheses surrounding the
5312 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005313 // C++ [over.over]p1:
5314 // [...] The overloaded function name can be preceded by the &
5315 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005316 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5317 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5318 if (OvlExpr->hasExplicitTemplateArgs()) {
5319 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5320 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005321 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005322
5323 // We expect a pointer or reference to function, or a function pointer.
5324 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5325 if (!FunctionType->isFunctionType()) {
5326 if (Complain)
5327 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5328 << OvlExpr->getName() << ToType;
5329
5330 return 0;
5331 }
5332
5333 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005334
Douglas Gregorcd695e52008-11-10 20:40:00 +00005335 // Look through all of the overloaded functions, searching for one
5336 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005337 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005338 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5339
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005340 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005341 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5342 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005343 // Look through any using declarations to find the underlying function.
5344 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5345
Douglas Gregorcd695e52008-11-10 20:40:00 +00005346 // C++ [over.over]p3:
5347 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005348 // targets of type "pointer-to-function" or "reference-to-function."
5349 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005350 // type "pointer-to-member-function."
5351 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005352
Mike Stump11289f42009-09-09 15:08:12 +00005353 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005354 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005355 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005356 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005357 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005358 // static when converting to member pointer.
5359 if (Method->isStatic() == IsMember)
5360 continue;
5361 } else if (IsMember)
5362 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005363
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005364 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005365 // If the name is a function template, template argument deduction is
5366 // done (14.8.2.2), and if the argument deduction succeeds, the
5367 // resulting template argument list is used to generate a single
5368 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005369 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005370 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005371 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005372 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005373 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005374 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005375 FunctionType, Specialization, Info)) {
5376 // FIXME: make a note of the failed deduction for diagnostics.
5377 (void)Result;
5378 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005379 // FIXME: If the match isn't exact, shouldn't we just drop this as
5380 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005381 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005382 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005383 Matches.push_back(std::make_pair(I.getPair(),
5384 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005385 }
John McCalld14a8642009-11-21 08:51:07 +00005386
5387 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005388 }
Mike Stump11289f42009-09-09 15:08:12 +00005389
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005390 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005391 // Skip non-static functions when converting to pointer, and static
5392 // when converting to member pointer.
5393 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005394 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005395
5396 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005397 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005398 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005399 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005400 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005401
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005402 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005403 QualType ResultTy;
5404 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5405 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5406 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005407 Matches.push_back(std::make_pair(I.getPair(),
5408 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005409 FoundNonTemplateFunction = true;
5410 }
Mike Stump11289f42009-09-09 15:08:12 +00005411 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005412 }
5413
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005414 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005415 if (Matches.empty()) {
5416 if (Complain) {
5417 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5418 << OvlExpr->getName() << FunctionType;
5419 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5420 E = OvlExpr->decls_end();
5421 I != E; ++I)
5422 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5423 NoteOverloadCandidate(F);
5424 }
5425
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005426 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005427 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005428 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005429 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005430 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005431 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005432 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005433 return Result;
5434 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005435
5436 // C++ [over.over]p4:
5437 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005438 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005439 // [...] and any given function template specialization F1 is
5440 // eliminated if the set contains a second function template
5441 // specialization whose function template is more specialized
5442 // than the function template of F1 according to the partial
5443 // ordering rules of 14.5.5.2.
5444
5445 // The algorithm specified above is quadratic. We instead use a
5446 // two-pass algorithm (similar to the one used to identify the
5447 // best viable function in an overload set) that identifies the
5448 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005449
5450 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5451 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5452 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005453
5454 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005455 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005456 TPOC_Other, From->getLocStart(),
5457 PDiag(),
5458 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005459 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005460 PDiag(diag::note_ovl_candidate)
5461 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005462 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005463 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005464 FoundResult = Matches[Result - MatchesCopy.begin()].first;
5465 if (Complain)
5466 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00005467 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005468 }
Mike Stump11289f42009-09-09 15:08:12 +00005469
Douglas Gregorfae1d712009-09-26 03:56:17 +00005470 // [...] any function template specializations in the set are
5471 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005472 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005473 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005474 ++I;
5475 else {
John McCalla0296f72010-03-19 07:35:19 +00005476 Matches[I] = Matches[--N];
5477 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005478 }
5479 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005480
Mike Stump11289f42009-09-09 15:08:12 +00005481 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005482 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005483 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005484 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005485 FoundResult = Matches[0].first;
John McCall58cc69d2010-01-27 01:50:18 +00005486 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00005487 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5488 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005489 }
Mike Stump11289f42009-09-09 15:08:12 +00005490
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005491 // FIXME: We should probably return the same thing that BestViableFunction
5492 // returns (even if we issue the diagnostics here).
5493 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005494 << Matches[0].second->getDeclName();
5495 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5496 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005497 return 0;
5498}
5499
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005500/// \brief Given an expression that refers to an overloaded function, try to
5501/// resolve that overloaded function expression down to a single function.
5502///
5503/// This routine can only resolve template-ids that refer to a single function
5504/// template, where that template-id refers to a single template whose template
5505/// arguments are either provided by the template-id or have defaults,
5506/// as described in C++0x [temp.arg.explicit]p3.
5507FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5508 // C++ [over.over]p1:
5509 // [...] [Note: any redundant set of parentheses surrounding the
5510 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005511 // C++ [over.over]p1:
5512 // [...] The overloaded function name can be preceded by the &
5513 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005514
5515 if (From->getType() != Context.OverloadTy)
5516 return 0;
5517
5518 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005519
5520 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005521 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005522 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005523
5524 TemplateArgumentListInfo ExplicitTemplateArgs;
5525 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005526
5527 // Look through all of the overloaded functions, searching for one
5528 // whose type matches exactly.
5529 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005530 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5531 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005532 // C++0x [temp.arg.explicit]p3:
5533 // [...] In contexts where deduction is done and fails, or in contexts
5534 // where deduction is not done, if a template argument list is
5535 // specified and it, along with any default template arguments,
5536 // identifies a single function template specialization, then the
5537 // template-id is an lvalue for the function template specialization.
5538 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5539
5540 // C++ [over.over]p2:
5541 // If the name is a function template, template argument deduction is
5542 // done (14.8.2.2), and if the argument deduction succeeds, the
5543 // resulting template argument list is used to generate a single
5544 // function template specialization, which is added to the set of
5545 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005546 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005547 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005548 if (TemplateDeductionResult Result
5549 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5550 Specialization, Info)) {
5551 // FIXME: make a note of the failed deduction for diagnostics.
5552 (void)Result;
5553 continue;
5554 }
5555
5556 // Multiple matches; we can't resolve to a single declaration.
5557 if (Matched)
5558 return 0;
5559
5560 Matched = Specialization;
5561 }
5562
5563 return Matched;
5564}
5565
Douglas Gregorcabea402009-09-22 15:41:20 +00005566/// \brief Add a single candidate to the overload set.
5567static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005568 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005569 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005570 Expr **Args, unsigned NumArgs,
5571 OverloadCandidateSet &CandidateSet,
5572 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005573 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005574 if (isa<UsingShadowDecl>(Callee))
5575 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5576
Douglas Gregorcabea402009-09-22 15:41:20 +00005577 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005578 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005579 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005580 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005581 return;
John McCalld14a8642009-11-21 08:51:07 +00005582 }
5583
5584 if (FunctionTemplateDecl *FuncTemplate
5585 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005586 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5587 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005588 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005589 return;
5590 }
5591
5592 assert(false && "unhandled case in overloaded call candidate");
5593
5594 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005595}
5596
5597/// \brief Add the overload candidates named by callee and/or found by argument
5598/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005599void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005600 Expr **Args, unsigned NumArgs,
5601 OverloadCandidateSet &CandidateSet,
5602 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005603
5604#ifndef NDEBUG
5605 // Verify that ArgumentDependentLookup is consistent with the rules
5606 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005607 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005608 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5609 // and let Y be the lookup set produced by argument dependent
5610 // lookup (defined as follows). If X contains
5611 //
5612 // -- a declaration of a class member, or
5613 //
5614 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005615 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005616 //
5617 // -- a declaration that is neither a function or a function
5618 // template
5619 //
5620 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005621
John McCall57500772009-12-16 12:17:52 +00005622 if (ULE->requiresADL()) {
5623 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5624 E = ULE->decls_end(); I != E; ++I) {
5625 assert(!(*I)->getDeclContext()->isRecord());
5626 assert(isa<UsingShadowDecl>(*I) ||
5627 !(*I)->getDeclContext()->isFunctionOrMethod());
5628 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005629 }
5630 }
5631#endif
5632
John McCall57500772009-12-16 12:17:52 +00005633 // It would be nice to avoid this copy.
5634 TemplateArgumentListInfo TABuffer;
5635 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5636 if (ULE->hasExplicitTemplateArgs()) {
5637 ULE->copyTemplateArgumentsInto(TABuffer);
5638 ExplicitTemplateArgs = &TABuffer;
5639 }
5640
5641 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5642 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005643 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005644 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005645 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005646
John McCall57500772009-12-16 12:17:52 +00005647 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005648 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5649 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005650 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005651 CandidateSet,
5652 PartialOverloading);
5653}
John McCalld681c392009-12-16 08:11:27 +00005654
John McCall57500772009-12-16 12:17:52 +00005655static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5656 Expr **Args, unsigned NumArgs) {
5657 Fn->Destroy(SemaRef.Context);
5658 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5659 Args[Arg]->Destroy(SemaRef.Context);
5660 return SemaRef.ExprError();
5661}
5662
John McCalld681c392009-12-16 08:11:27 +00005663/// Attempts to recover from a call where no functions were found.
5664///
5665/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005666static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005667BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005668 UnresolvedLookupExpr *ULE,
5669 SourceLocation LParenLoc,
5670 Expr **Args, unsigned NumArgs,
5671 SourceLocation *CommaLocs,
5672 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005673
5674 CXXScopeSpec SS;
5675 if (ULE->getQualifier()) {
5676 SS.setScopeRep(ULE->getQualifier());
5677 SS.setRange(ULE->getQualifierRange());
5678 }
5679
John McCall57500772009-12-16 12:17:52 +00005680 TemplateArgumentListInfo TABuffer;
5681 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5682 if (ULE->hasExplicitTemplateArgs()) {
5683 ULE->copyTemplateArgumentsInto(TABuffer);
5684 ExplicitTemplateArgs = &TABuffer;
5685 }
5686
John McCalld681c392009-12-16 08:11:27 +00005687 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5688 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005689 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005690 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005691
John McCall57500772009-12-16 12:17:52 +00005692 assert(!R.empty() && "lookup results empty despite recovery");
5693
5694 // Build an implicit member call if appropriate. Just drop the
5695 // casts and such from the call, we don't really care.
5696 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5697 if ((*R.begin())->isCXXClassMember())
5698 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5699 else if (ExplicitTemplateArgs)
5700 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5701 else
5702 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5703
5704 if (NewFn.isInvalid())
5705 return Destroy(SemaRef, Fn, Args, NumArgs);
5706
5707 Fn->Destroy(SemaRef.Context);
5708
5709 // This shouldn't cause an infinite loop because we're giving it
5710 // an expression with non-empty lookup results, which should never
5711 // end up here.
5712 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5713 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5714 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005715}
Douglas Gregorcabea402009-09-22 15:41:20 +00005716
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005717/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005718/// (which eventually refers to the declaration Func) and the call
5719/// arguments Args/NumArgs, attempt to resolve the function call down
5720/// to a specific function. If overload resolution succeeds, returns
5721/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005722/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005723/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005724Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005725Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005726 SourceLocation LParenLoc,
5727 Expr **Args, unsigned NumArgs,
5728 SourceLocation *CommaLocs,
5729 SourceLocation RParenLoc) {
5730#ifndef NDEBUG
5731 if (ULE->requiresADL()) {
5732 // To do ADL, we must have found an unqualified name.
5733 assert(!ULE->getQualifier() && "qualified name with ADL");
5734
5735 // We don't perform ADL for implicit declarations of builtins.
5736 // Verify that this was correctly set up.
5737 FunctionDecl *F;
5738 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5739 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5740 F->getBuiltinID() && F->isImplicit())
5741 assert(0 && "performing ADL for builtin");
5742
5743 // We don't perform ADL in C.
5744 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5745 }
5746#endif
5747
John McCallbc077cf2010-02-08 23:07:23 +00005748 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005749
John McCall57500772009-12-16 12:17:52 +00005750 // Add the functions denoted by the callee to the set of candidate
5751 // functions, including those from argument-dependent lookup.
5752 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005753
5754 // If we found nothing, try to recover.
5755 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5756 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005757 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005758 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00005759 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005760
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005761 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005762 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005763 case OR_Success: {
5764 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00005765 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall16df1e52010-03-30 21:47:33 +00005766 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00005767 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5768 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005769
5770 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005771 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005772 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005773 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005774 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005775 break;
5776
5777 case OR_Ambiguous:
5778 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005779 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005780 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005781 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005782
5783 case OR_Deleted:
5784 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5785 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005786 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005787 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005788 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005789 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005790 }
5791
5792 // Overload resolution failed. Destroy all of the subexpressions and
5793 // return NULL.
5794 Fn->Destroy(Context);
5795 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5796 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005797 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005798}
5799
John McCall4c4c1df2010-01-26 03:27:55 +00005800static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005801 return Functions.size() > 1 ||
5802 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5803}
5804
Douglas Gregor084d8552009-03-13 23:49:33 +00005805/// \brief Create a unary operation that may resolve to an overloaded
5806/// operator.
5807///
5808/// \param OpLoc The location of the operator itself (e.g., '*').
5809///
5810/// \param OpcIn The UnaryOperator::Opcode that describes this
5811/// operator.
5812///
5813/// \param Functions The set of non-member functions that will be
5814/// considered by overload resolution. The caller needs to build this
5815/// set based on the context using, e.g.,
5816/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5817/// set should not contain any member functions; those will be added
5818/// by CreateOverloadedUnaryOp().
5819///
5820/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005821Sema::OwningExprResult
5822Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5823 const UnresolvedSetImpl &Fns,
5824 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005825 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5826 Expr *Input = (Expr *)input.get();
5827
5828 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5829 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5830 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5831
5832 Expr *Args[2] = { Input, 0 };
5833 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005834
Douglas Gregor084d8552009-03-13 23:49:33 +00005835 // For post-increment and post-decrement, add the implicit '0' as
5836 // the second argument, so that we know this is a post-increment or
5837 // post-decrement.
5838 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5839 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005840 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005841 SourceLocation());
5842 NumArgs = 2;
5843 }
5844
5845 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005846 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005847 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005848 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005849 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005850 /*ADL*/ true, IsOverloaded(Fns));
5851 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005852
Douglas Gregor084d8552009-03-13 23:49:33 +00005853 input.release();
5854 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5855 &Args[0], NumArgs,
5856 Context.DependentTy,
5857 OpLoc));
5858 }
5859
5860 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005861 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005862
5863 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005864 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005865
5866 // Add operator candidates that are member functions.
5867 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5868
John McCall4c4c1df2010-01-26 03:27:55 +00005869 // Add candidates from ADL.
5870 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005871 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005872 /*ExplicitTemplateArgs*/ 0,
5873 CandidateSet);
5874
Douglas Gregor084d8552009-03-13 23:49:33 +00005875 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005876 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005877
5878 // Perform overload resolution.
5879 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005880 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005881 case OR_Success: {
5882 // We found a built-in operator or an overloaded operator.
5883 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005884
Douglas Gregor084d8552009-03-13 23:49:33 +00005885 if (FnDecl) {
5886 // We matched an overloaded operator. Build a call to that
5887 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005888
Douglas Gregor084d8552009-03-13 23:49:33 +00005889 // Convert the arguments.
5890 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00005891 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00005892
John McCall16df1e52010-03-30 21:47:33 +00005893 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5894 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005895 return ExprError();
5896 } else {
5897 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005898 OwningExprResult InputInit
5899 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005900 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005901 SourceLocation(),
5902 move(input));
5903 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005904 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005905
Douglas Gregore6600372009-12-23 17:40:29 +00005906 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005907 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005908 }
5909
5910 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005911 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005912
Douglas Gregor084d8552009-03-13 23:49:33 +00005913 // Build the actual expression node.
5914 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5915 SourceLocation());
5916 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005917
Douglas Gregor084d8552009-03-13 23:49:33 +00005918 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005919 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005920 ExprOwningPtr<CallExpr> TheCall(this,
5921 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005922 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005923
5924 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5925 FnDecl))
5926 return ExprError();
5927
5928 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005929 } else {
5930 // We matched a built-in operator. Convert the arguments, then
5931 // break out so that we will build the appropriate built-in
5932 // operator node.
5933 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005934 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005935 return ExprError();
5936
5937 break;
5938 }
5939 }
5940
5941 case OR_No_Viable_Function:
5942 // No viable function; fall through to handling this as a
5943 // built-in operator, which will produce an error message for us.
5944 break;
5945
5946 case OR_Ambiguous:
5947 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5948 << UnaryOperator::getOpcodeStr(Opc)
5949 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005950 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005951 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005952 return ExprError();
5953
5954 case OR_Deleted:
5955 Diag(OpLoc, diag::err_ovl_deleted_oper)
5956 << Best->Function->isDeleted()
5957 << UnaryOperator::getOpcodeStr(Opc)
5958 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005959 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005960 return ExprError();
5961 }
5962
5963 // Either we found no viable overloaded operator or we matched a
5964 // built-in operator. In either case, fall through to trying to
5965 // build a built-in operation.
5966 input.release();
5967 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5968}
5969
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005970/// \brief Create a binary operation that may resolve to an overloaded
5971/// operator.
5972///
5973/// \param OpLoc The location of the operator itself (e.g., '+').
5974///
5975/// \param OpcIn The BinaryOperator::Opcode that describes this
5976/// operator.
5977///
5978/// \param Functions The set of non-member functions that will be
5979/// considered by overload resolution. The caller needs to build this
5980/// set based on the context using, e.g.,
5981/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5982/// set should not contain any member functions; those will be added
5983/// by CreateOverloadedBinOp().
5984///
5985/// \param LHS Left-hand argument.
5986/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005987Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005988Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005989 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005990 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005991 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005992 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005993 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005994
5995 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5996 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5997 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5998
5999 // If either side is type-dependent, create an appropriate dependent
6000 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006001 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006002 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006003 // If there are no functions to store, just build a dependent
6004 // BinaryOperator or CompoundAssignment.
6005 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6006 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6007 Context.DependentTy, OpLoc));
6008
6009 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6010 Context.DependentTy,
6011 Context.DependentTy,
6012 Context.DependentTy,
6013 OpLoc));
6014 }
John McCall4c4c1df2010-01-26 03:27:55 +00006015
6016 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006017 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006018 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006019 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006020 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006021 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006022
John McCall4c4c1df2010-01-26 03:27:55 +00006023 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006024 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006025 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006026 Context.DependentTy,
6027 OpLoc));
6028 }
6029
6030 // If this is the .* operator, which is not overloadable, just
6031 // create a built-in binary operator.
6032 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006033 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006034
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006035 // If this is the assignment operator, we only perform overload resolution
6036 // if the left-hand side is a class or enumeration type. This is actually
6037 // a hack. The standard requires that we do overload resolution between the
6038 // various built-in candidates, but as DR507 points out, this can lead to
6039 // problems. So we do it this way, which pretty much follows what GCC does.
6040 // Note that we go the traditional code path for compound assignment forms.
6041 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006042 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006043
Douglas Gregor084d8552009-03-13 23:49:33 +00006044 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006045 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006046
6047 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006048 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006049
6050 // Add operator candidates that are member functions.
6051 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6052
John McCall4c4c1df2010-01-26 03:27:55 +00006053 // Add candidates from ADL.
6054 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6055 Args, 2,
6056 /*ExplicitTemplateArgs*/ 0,
6057 CandidateSet);
6058
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006059 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006060 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006061
6062 // Perform overload resolution.
6063 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006064 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006065 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006066 // We found a built-in operator or an overloaded operator.
6067 FunctionDecl *FnDecl = Best->Function;
6068
6069 if (FnDecl) {
6070 // We matched an overloaded operator. Build a call to that
6071 // operator.
6072
6073 // Convert the arguments.
6074 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006075 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006076 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006077
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006078 OwningExprResult Arg1
6079 = PerformCopyInitialization(
6080 InitializedEntity::InitializeParameter(
6081 FnDecl->getParamDecl(0)),
6082 SourceLocation(),
6083 Owned(Args[1]));
6084 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006085 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006086
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006087 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006088 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006089 return ExprError();
6090
6091 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006092 } else {
6093 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006094 OwningExprResult Arg0
6095 = PerformCopyInitialization(
6096 InitializedEntity::InitializeParameter(
6097 FnDecl->getParamDecl(0)),
6098 SourceLocation(),
6099 Owned(Args[0]));
6100 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006101 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006102
6103 OwningExprResult Arg1
6104 = PerformCopyInitialization(
6105 InitializedEntity::InitializeParameter(
6106 FnDecl->getParamDecl(1)),
6107 SourceLocation(),
6108 Owned(Args[1]));
6109 if (Arg1.isInvalid())
6110 return ExprError();
6111 Args[0] = LHS = Arg0.takeAs<Expr>();
6112 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006113 }
6114
6115 // Determine the result type
6116 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006117 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006118 ResultTy = ResultTy.getNonReferenceType();
6119
6120 // Build the actual expression node.
6121 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006122 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006123 UsualUnaryConversions(FnExpr);
6124
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006125 ExprOwningPtr<CXXOperatorCallExpr>
6126 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6127 Args, 2, ResultTy,
6128 OpLoc));
6129
6130 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6131 FnDecl))
6132 return ExprError();
6133
6134 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006135 } else {
6136 // We matched a built-in operator. Convert the arguments, then
6137 // break out so that we will build the appropriate built-in
6138 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006139 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006140 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006141 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006142 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006143 return ExprError();
6144
6145 break;
6146 }
6147 }
6148
Douglas Gregor66950a32009-09-30 21:46:01 +00006149 case OR_No_Viable_Function: {
6150 // C++ [over.match.oper]p9:
6151 // If the operator is the operator , [...] and there are no
6152 // viable functions, then the operator is assumed to be the
6153 // built-in operator and interpreted according to clause 5.
6154 if (Opc == BinaryOperator::Comma)
6155 break;
6156
Sebastian Redl027de2a2009-05-21 11:50:50 +00006157 // For class as left operand for assignment or compound assigment operator
6158 // do not fall through to handling in built-in, but report that no overloaded
6159 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006160 OwningExprResult Result = ExprError();
6161 if (Args[0]->getType()->isRecordType() &&
6162 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006163 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6164 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006165 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006166 } else {
6167 // No viable function; try to create a built-in operation, which will
6168 // produce an error. Then, show the non-viable candidates.
6169 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006170 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006171 assert(Result.isInvalid() &&
6172 "C++ binary operator overloading is missing candidates!");
6173 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006174 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006175 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006176 return move(Result);
6177 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006178
6179 case OR_Ambiguous:
6180 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6181 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006182 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006183 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006184 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006185 return ExprError();
6186
6187 case OR_Deleted:
6188 Diag(OpLoc, diag::err_ovl_deleted_oper)
6189 << Best->Function->isDeleted()
6190 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006191 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006192 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006193 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006194 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006195
Douglas Gregor66950a32009-09-30 21:46:01 +00006196 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006197 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006198}
6199
Sebastian Redladba46e2009-10-29 20:17:01 +00006200Action::OwningExprResult
6201Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6202 SourceLocation RLoc,
6203 ExprArg Base, ExprArg Idx) {
6204 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6205 static_cast<Expr*>(Idx.get()) };
6206 DeclarationName OpName =
6207 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6208
6209 // If either side is type-dependent, create an appropriate dependent
6210 // expression.
6211 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6212
John McCall58cc69d2010-01-27 01:50:18 +00006213 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006214 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006215 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006216 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006217 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006218 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006219
6220 Base.release();
6221 Idx.release();
6222 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6223 Args, 2,
6224 Context.DependentTy,
6225 RLoc));
6226 }
6227
6228 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006229 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006230
6231 // Subscript can only be overloaded as a member function.
6232
6233 // Add operator candidates that are member functions.
6234 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6235
6236 // Add builtin operator candidates.
6237 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6238
6239 // Perform overload resolution.
6240 OverloadCandidateSet::iterator Best;
6241 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6242 case OR_Success: {
6243 // We found a built-in operator or an overloaded operator.
6244 FunctionDecl *FnDecl = Best->Function;
6245
6246 if (FnDecl) {
6247 // We matched an overloaded operator. Build a call to that
6248 // operator.
6249
John McCalla0296f72010-03-19 07:35:19 +00006250 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +00006251
Sebastian Redladba46e2009-10-29 20:17:01 +00006252 // Convert the arguments.
6253 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006254 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006255 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006256 return ExprError();
6257
Anders Carlssona68e51e2010-01-29 18:37:50 +00006258 // Convert the arguments.
6259 OwningExprResult InputInit
6260 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6261 FnDecl->getParamDecl(0)),
6262 SourceLocation(),
6263 Owned(Args[1]));
6264 if (InputInit.isInvalid())
6265 return ExprError();
6266
6267 Args[1] = InputInit.takeAs<Expr>();
6268
Sebastian Redladba46e2009-10-29 20:17:01 +00006269 // Determine the result type
6270 QualType ResultTy
6271 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6272 ResultTy = ResultTy.getNonReferenceType();
6273
6274 // Build the actual expression node.
6275 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6276 LLoc);
6277 UsualUnaryConversions(FnExpr);
6278
6279 Base.release();
6280 Idx.release();
6281 ExprOwningPtr<CXXOperatorCallExpr>
6282 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6283 FnExpr, Args, 2,
6284 ResultTy, RLoc));
6285
6286 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6287 FnDecl))
6288 return ExprError();
6289
6290 return MaybeBindToTemporary(TheCall.release());
6291 } else {
6292 // We matched a built-in operator. Convert the arguments, then
6293 // break out so that we will build the appropriate built-in
6294 // operator node.
6295 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006296 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006297 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006298 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006299 return ExprError();
6300
6301 break;
6302 }
6303 }
6304
6305 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006306 if (CandidateSet.empty())
6307 Diag(LLoc, diag::err_ovl_no_oper)
6308 << Args[0]->getType() << /*subscript*/ 0
6309 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6310 else
6311 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6312 << Args[0]->getType()
6313 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006314 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006315 "[]", LLoc);
6316 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006317 }
6318
6319 case OR_Ambiguous:
6320 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6321 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006322 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006323 "[]", LLoc);
6324 return ExprError();
6325
6326 case OR_Deleted:
6327 Diag(LLoc, diag::err_ovl_deleted_oper)
6328 << Best->Function->isDeleted() << "[]"
6329 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006330 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006331 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006332 return ExprError();
6333 }
6334
6335 // We matched a built-in operator; build it.
6336 Base.release();
6337 Idx.release();
6338 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6339 Owned(Args[1]), RLoc);
6340}
6341
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006342/// BuildCallToMemberFunction - Build a call to a member
6343/// function. MemExpr is the expression that refers to the member
6344/// function (and includes the object parameter), Args/NumArgs are the
6345/// arguments to the function call (not including the object
6346/// parameter). The caller needs to validate that the member
6347/// expression refers to a member function or an overloaded member
6348/// function.
John McCall2d74de92009-12-01 22:10:20 +00006349Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006350Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6351 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006352 unsigned NumArgs, SourceLocation *CommaLocs,
6353 SourceLocation RParenLoc) {
6354 // Dig out the member expression. This holds both the object
6355 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006356 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6357
John McCall10eae182009-11-30 22:42:35 +00006358 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006359 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006360 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006361 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006362 if (isa<MemberExpr>(NakedMemExpr)) {
6363 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006364 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006365 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006366 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006367 } else {
6368 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006369 Qualifier = UnresExpr->getQualifier();
6370
John McCall6e9f8f62009-12-03 04:06:58 +00006371 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006372
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006373 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006374 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006375
John McCall2d74de92009-12-01 22:10:20 +00006376 // FIXME: avoid copy.
6377 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6378 if (UnresExpr->hasExplicitTemplateArgs()) {
6379 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6380 TemplateArgs = &TemplateArgsBuffer;
6381 }
6382
John McCall10eae182009-11-30 22:42:35 +00006383 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6384 E = UnresExpr->decls_end(); I != E; ++I) {
6385
John McCall6e9f8f62009-12-03 04:06:58 +00006386 NamedDecl *Func = *I;
6387 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6388 if (isa<UsingShadowDecl>(Func))
6389 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6390
John McCall10eae182009-11-30 22:42:35 +00006391 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006392 // If explicit template arguments were provided, we can't call a
6393 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006394 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006395 continue;
6396
John McCalla0296f72010-03-19 07:35:19 +00006397 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006398 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006399 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006400 } else {
John McCall10eae182009-11-30 22:42:35 +00006401 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006402 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006403 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006404 CandidateSet,
6405 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006406 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006407 }
Mike Stump11289f42009-09-09 15:08:12 +00006408
John McCall10eae182009-11-30 22:42:35 +00006409 DeclarationName DeclName = UnresExpr->getMemberName();
6410
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006411 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006412 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006413 case OR_Success:
6414 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006415 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006416 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006417 break;
6418
6419 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006420 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006421 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006422 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006423 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006424 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006425 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006426
6427 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006428 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006429 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006430 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006431 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006432 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006433
6434 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006435 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006436 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006437 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006438 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006439 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006440 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006441 }
6442
John McCall16df1e52010-03-30 21:47:33 +00006443 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006444
John McCall2d74de92009-12-01 22:10:20 +00006445 // If overload resolution picked a static member, build a
6446 // non-member call based on that function.
6447 if (Method->isStatic()) {
6448 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6449 Args, NumArgs, RParenLoc);
6450 }
6451
John McCall10eae182009-11-30 22:42:35 +00006452 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006453 }
6454
6455 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006456 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006457 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006458 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006459 Method->getResultType().getNonReferenceType(),
6460 RParenLoc));
6461
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006462 // Check for a valid return type.
6463 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6464 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006465 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006466
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006467 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006468 // We only need to do this if there was actually an overload; otherwise
6469 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006470 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006471 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006472 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6473 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006474 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006475 MemExpr->setBase(ObjectArg);
6476
6477 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006478 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006479 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006480 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006481 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006482
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006483 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006484 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006485
John McCall2d74de92009-12-01 22:10:20 +00006486 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006487}
6488
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006489/// BuildCallToObjectOfClassType - Build a call to an object of class
6490/// type (C++ [over.call.object]), which can end up invoking an
6491/// overloaded function call operator (@c operator()) or performing a
6492/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006493Sema::ExprResult
6494Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006495 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006496 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006497 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006498 SourceLocation RParenLoc) {
6499 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006500 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006501
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006502 // C++ [over.call.object]p1:
6503 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006504 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006505 // candidate functions includes at least the function call
6506 // operators of T. The function call operators of T are obtained by
6507 // ordinary lookup of the name operator() in the context of
6508 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006509 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006510 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006511
6512 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006513 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006514 << Object->getSourceRange()))
6515 return true;
6516
John McCall27b18f82009-11-17 02:14:36 +00006517 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6518 LookupQualifiedName(R, Record->getDecl());
6519 R.suppressDiagnostics();
6520
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006521 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006522 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006523 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006524 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006525 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006526 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006527
Douglas Gregorab7897a2008-11-19 22:57:39 +00006528 // C++ [over.call.object]p2:
6529 // In addition, for each conversion function declared in T of the
6530 // form
6531 //
6532 // operator conversion-type-id () cv-qualifier;
6533 //
6534 // where cv-qualifier is the same cv-qualification as, or a
6535 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006536 // denotes the type "pointer to function of (P1,...,Pn) returning
6537 // R", or the type "reference to pointer to function of
6538 // (P1,...,Pn) returning R", or the type "reference to function
6539 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006540 // is also considered as a candidate function. Similarly,
6541 // surrogate call functions are added to the set of candidate
6542 // functions for each conversion function declared in an
6543 // accessible base class provided the function is not hidden
6544 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006545 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006546 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006547 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006548 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006549 NamedDecl *D = *I;
6550 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6551 if (isa<UsingShadowDecl>(D))
6552 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6553
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006554 // Skip over templated conversion functions; they aren't
6555 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006556 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006557 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006558
John McCall6e9f8f62009-12-03 04:06:58 +00006559 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006560
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006561 // Strip the reference type (if any) and then the pointer type (if
6562 // any) to get down to what might be a function type.
6563 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6564 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6565 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006566
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006567 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006568 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006569 Object->getType(), Args, NumArgs,
6570 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006571 }
Mike Stump11289f42009-09-09 15:08:12 +00006572
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006573 // Perform overload resolution.
6574 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006575 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006576 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006577 // Overload resolution succeeded; we'll build the appropriate call
6578 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006579 break;
6580
6581 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006582 if (CandidateSet.empty())
6583 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6584 << Object->getType() << /*call*/ 1
6585 << Object->getSourceRange();
6586 else
6587 Diag(Object->getSourceRange().getBegin(),
6588 diag::err_ovl_no_viable_object_call)
6589 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006590 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006591 break;
6592
6593 case OR_Ambiguous:
6594 Diag(Object->getSourceRange().getBegin(),
6595 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006596 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006597 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006598 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006599
6600 case OR_Deleted:
6601 Diag(Object->getSourceRange().getBegin(),
6602 diag::err_ovl_deleted_object_call)
6603 << Best->Function->isDeleted()
6604 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006605 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006606 break;
Mike Stump11289f42009-09-09 15:08:12 +00006607 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006608
Douglas Gregorab7897a2008-11-19 22:57:39 +00006609 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006610 // We had an error; delete all of the subexpressions and return
6611 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006612 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006613 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006614 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006615 return true;
6616 }
6617
Douglas Gregorab7897a2008-11-19 22:57:39 +00006618 if (Best->Function == 0) {
6619 // Since there is no function declaration, this is one of the
6620 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006621 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006622 = cast<CXXConversionDecl>(
6623 Best->Conversions[0].UserDefined.ConversionFunction);
6624
John McCalla0296f72010-03-19 07:35:19 +00006625 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006626
Douglas Gregorab7897a2008-11-19 22:57:39 +00006627 // We selected one of the surrogate functions that converts the
6628 // object parameter to a function pointer. Perform the conversion
6629 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006630
6631 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006632 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006633 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6634 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006635
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006636 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006637 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006638 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006639 }
6640
John McCalla0296f72010-03-19 07:35:19 +00006641 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006642
Douglas Gregorab7897a2008-11-19 22:57:39 +00006643 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6644 // that calls this method, using Object for the implicit object
6645 // parameter and passing along the remaining arguments.
6646 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006647 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006648
6649 unsigned NumArgsInProto = Proto->getNumArgs();
6650 unsigned NumArgsToCheck = NumArgs;
6651
6652 // Build the full argument list for the method call (the
6653 // implicit object parameter is placed at the beginning of the
6654 // list).
6655 Expr **MethodArgs;
6656 if (NumArgs < NumArgsInProto) {
6657 NumArgsToCheck = NumArgsInProto;
6658 MethodArgs = new Expr*[NumArgsInProto + 1];
6659 } else {
6660 MethodArgs = new Expr*[NumArgs + 1];
6661 }
6662 MethodArgs[0] = Object;
6663 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6664 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006665
6666 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006667 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006668 UsualUnaryConversions(NewFn);
6669
6670 // Once we've built TheCall, all of the expressions are properly
6671 // owned.
6672 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006673 ExprOwningPtr<CXXOperatorCallExpr>
6674 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006675 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006676 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006677 delete [] MethodArgs;
6678
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006679 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6680 Method))
6681 return true;
6682
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006683 // We may have default arguments. If so, we need to allocate more
6684 // slots in the call for them.
6685 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006686 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006687 else if (NumArgs > NumArgsInProto)
6688 NumArgsToCheck = NumArgsInProto;
6689
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006690 bool IsError = false;
6691
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006692 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006693 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006694 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006695 TheCall->setArg(0, Object);
6696
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006697
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006698 // Check the argument types.
6699 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006700 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006701 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006702 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006703
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006704 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006705
6706 OwningExprResult InputInit
6707 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6708 Method->getParamDecl(i)),
6709 SourceLocation(), Owned(Arg));
6710
6711 IsError |= InputInit.isInvalid();
6712 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006713 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006714 OwningExprResult DefArg
6715 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6716 if (DefArg.isInvalid()) {
6717 IsError = true;
6718 break;
6719 }
6720
6721 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006722 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006723
6724 TheCall->setArg(i + 1, Arg);
6725 }
6726
6727 // If this is a variadic call, handle args passed through "...".
6728 if (Proto->isVariadic()) {
6729 // Promote the arguments (C99 6.5.2.2p7).
6730 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6731 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006732 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006733 TheCall->setArg(i + 1, Arg);
6734 }
6735 }
6736
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006737 if (IsError) return true;
6738
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006739 if (CheckFunctionCall(Method, TheCall.get()))
6740 return true;
6741
Douglas Gregore5e775b2010-04-13 15:50:39 +00006742 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006743}
6744
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006745/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006746/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006747/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006748Sema::OwningExprResult
6749Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6750 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006751 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006752
John McCallbc077cf2010-02-08 23:07:23 +00006753 SourceLocation Loc = Base->getExprLoc();
6754
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006755 // C++ [over.ref]p1:
6756 //
6757 // [...] An expression x->m is interpreted as (x.operator->())->m
6758 // for a class object x of type T if T::operator->() exists and if
6759 // the operator is selected as the best match function by the
6760 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006761 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006762 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006763 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006764
John McCallbc077cf2010-02-08 23:07:23 +00006765 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006766 PDiag(diag::err_typecheck_incomplete_tag)
6767 << Base->getSourceRange()))
6768 return ExprError();
6769
John McCall27b18f82009-11-17 02:14:36 +00006770 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6771 LookupQualifiedName(R, BaseRecord->getDecl());
6772 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006773
6774 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006775 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006776 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006777 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006778 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006779
6780 // Perform overload resolution.
6781 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006782 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006783 case OR_Success:
6784 // Overload resolution succeeded; we'll build the call below.
6785 break;
6786
6787 case OR_No_Viable_Function:
6788 if (CandidateSet.empty())
6789 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006790 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006791 else
6792 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006793 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006794 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006795 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006796
6797 case OR_Ambiguous:
6798 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006799 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006800 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006801 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006802
6803 case OR_Deleted:
6804 Diag(OpLoc, diag::err_ovl_deleted_oper)
6805 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006806 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006807 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006808 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006809 }
6810
John McCalla0296f72010-03-19 07:35:19 +00006811 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6812
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006813 // Convert the object parameter.
6814 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006815 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6816 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006817 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006818
6819 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006820 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006821
6822 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006823 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6824 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006825 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006826
6827 QualType ResultTy = Method->getResultType().getNonReferenceType();
6828 ExprOwningPtr<CXXOperatorCallExpr>
6829 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6830 &Base, 1, ResultTy, OpLoc));
6831
6832 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6833 Method))
6834 return ExprError();
6835 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006836}
6837
Douglas Gregorcd695e52008-11-10 20:40:00 +00006838/// FixOverloadedFunctionReference - E is an expression that refers to
6839/// a C++ overloaded function (possibly with some parentheses and
6840/// perhaps a '&' around it). We have resolved the overloaded function
6841/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006842/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00006843Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00006844 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006845 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006846 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6847 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006848 if (SubExpr == PE->getSubExpr())
6849 return PE->Retain();
6850
6851 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6852 }
6853
6854 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006855 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6856 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006857 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006858 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006859 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006860 if (SubExpr == ICE->getSubExpr())
6861 return ICE->Retain();
6862
6863 return new (Context) ImplicitCastExpr(ICE->getType(),
6864 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00006865 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006866 ICE->isLvalueCast());
6867 }
6868
6869 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006870 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006871 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6873 if (Method->isStatic()) {
6874 // Do nothing: static member functions aren't any different
6875 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006876 } else {
John McCalle66edc12009-11-24 19:00:30 +00006877 // Fix the sub expression, which really has to be an
6878 // UnresolvedLookupExpr holding an overloaded member function
6879 // or template.
John McCall16df1e52010-03-30 21:47:33 +00006880 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6881 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00006882 if (SubExpr == UnOp->getSubExpr())
6883 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006884
John McCalld14a8642009-11-21 08:51:07 +00006885 assert(isa<DeclRefExpr>(SubExpr)
6886 && "fixed to something other than a decl ref");
6887 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6888 && "fixed to a member ref with no nested name qualifier");
6889
6890 // We have taken the address of a pointer to member
6891 // function. Perform the computation here so that we get the
6892 // appropriate pointer to member type.
6893 QualType ClassType
6894 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6895 QualType MemPtrType
6896 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6897
6898 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6899 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006900 }
6901 }
John McCall16df1e52010-03-30 21:47:33 +00006902 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6903 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006904 if (SubExpr == UnOp->getSubExpr())
6905 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006906
Douglas Gregor51c538b2009-11-20 19:42:02 +00006907 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6908 Context.getPointerType(SubExpr->getType()),
6909 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006910 }
John McCalld14a8642009-11-21 08:51:07 +00006911
6912 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006913 // FIXME: avoid copy.
6914 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006915 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006916 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6917 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006918 }
6919
John McCalld14a8642009-11-21 08:51:07 +00006920 return DeclRefExpr::Create(Context,
6921 ULE->getQualifier(),
6922 ULE->getQualifierRange(),
6923 Fn,
6924 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006925 Fn->getType(),
6926 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006927 }
6928
John McCall10eae182009-11-30 22:42:35 +00006929 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006930 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006931 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6932 if (MemExpr->hasExplicitTemplateArgs()) {
6933 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6934 TemplateArgs = &TemplateArgsBuffer;
6935 }
John McCall6b51f282009-11-23 01:53:49 +00006936
John McCall2d74de92009-12-01 22:10:20 +00006937 Expr *Base;
6938
6939 // If we're filling in
6940 if (MemExpr->isImplicitAccess()) {
6941 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6942 return DeclRefExpr::Create(Context,
6943 MemExpr->getQualifier(),
6944 MemExpr->getQualifierRange(),
6945 Fn,
6946 MemExpr->getMemberLoc(),
6947 Fn->getType(),
6948 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006949 } else {
6950 SourceLocation Loc = MemExpr->getMemberLoc();
6951 if (MemExpr->getQualifier())
6952 Loc = MemExpr->getQualifierRange().getBegin();
6953 Base = new (Context) CXXThisExpr(Loc,
6954 MemExpr->getBaseType(),
6955 /*isImplicit=*/true);
6956 }
John McCall2d74de92009-12-01 22:10:20 +00006957 } else
6958 Base = MemExpr->getBase()->Retain();
6959
6960 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006961 MemExpr->isArrow(),
6962 MemExpr->getQualifier(),
6963 MemExpr->getQualifierRange(),
6964 Fn,
John McCall16df1e52010-03-30 21:47:33 +00006965 Found,
John McCall6b51f282009-11-23 01:53:49 +00006966 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006967 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006968 Fn->getType());
6969 }
6970
Douglas Gregor51c538b2009-11-20 19:42:02 +00006971 assert(false && "Invalid reference to overloaded function");
6972 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006973}
6974
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006975Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00006976 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006977 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00006978 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006979}
6980
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006981} // end namespace clang