blob: 43321d639d08463f441ef4473e1f256fd66f7a87 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000083 ICR_Conversion
84 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
121 Deprecated = false;
122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
John McCall0d1da222010-01-12 00:44:57 +0000151 if (getToType()->isBooleanType() &&
152 (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();
167 QualType ToType = getToType();
Douglas Gregor5c407d92008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000229 OS << "'" << ConversionFunction->getNameAsString() << "'";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 break;
John McCall0d1da222010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000254 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261}
262
John McCall0d1da222010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
278
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000280// overload of the declarations in Old. This routine returns false if
281// New and Old cannot be overloaded, e.g., if New has the same
282// signature as some function in Old (C++ 1.3.10) or if the Old
283// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000284// it does return false, MatchedDecl will point to the decl that New
285// cannot be overloaded with. This decl may be a UsingShadowDecl on
286// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287//
288// Example: Given the following input:
289//
290// void f(int, float); // #1
291// void f(int, int); // #2
292// int f(int, int); // #3
293//
294// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296//
John McCall3d988d92009-12-02 08:47:38 +0000297// When we process #2, Old contains only the FunctionDecl for #1. By
298// comparing the parameter types, we see that #1 and #2 are overloaded
299// (since they have different signatures), so this routine returns
300// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301//
John McCall3d988d92009-12-02 08:47:38 +0000302// When we process #3, Old is an overload set containing #1 and #2. We
303// compare the signatures of #3 to #1 (they're overloaded, so we do
304// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
305// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000318 }
John McCall3d988d92009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000323 }
John McCall84d87672009-12-10 09:41:52 +0000324 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
325 // We can overload with these, which can show up when doing
326 // redeclaration checks for UsingDecls.
327 assert(Old.getLookupKind() == LookupUsingDeclName);
328 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
329 // Optimistically assume that an unresolved using decl will
330 // overload; if it doesn't, we'll have to diagnose during
331 // template instantiation.
332 } else {
John McCall1f82f242009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000338 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339 }
John McCall1f82f242009-11-18 22:49:29 +0000340
John McCalldaa3d6b2009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000342}
343
344bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
345 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
346 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
347
348 // C++ [temp.fct]p2:
349 // A function template can be overloaded with other function templates
350 // and with normal (non-template) functions.
351 if ((OldTemplate == 0) != (NewTemplate == 0))
352 return true;
353
354 // Is the function New an overload of the function Old?
355 QualType OldQType = Context.getCanonicalType(Old->getType());
356 QualType NewQType = Context.getCanonicalType(New->getType());
357
358 // Compare the signatures (C++ 1.3.10) of the two functions to
359 // determine whether they are overloads. If we find any mismatch
360 // in the signature, they are overloads.
361
362 // If either of these functions is a K&R-style function (no
363 // prototype), then we consider them to have matching signatures.
364 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
365 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
366 return false;
367
368 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
369 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
370
371 // The signature of a function includes the types of its
372 // parameters (C++ 1.3.10), which includes the presence or absence
373 // of the ellipsis; see C++ DR 357).
374 if (OldQType != NewQType &&
375 (OldType->getNumArgs() != NewType->getNumArgs() ||
376 OldType->isVariadic() != NewType->isVariadic() ||
377 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
378 NewType->arg_type_begin())))
379 return true;
380
381 // C++ [temp.over.link]p4:
382 // The signature of a function template consists of its function
383 // signature, its return type and its template parameter list. The names
384 // of the template parameters are significant only for establishing the
385 // relationship between the template parameters and the rest of the
386 // signature.
387 //
388 // We check the return type and template parameter lists for function
389 // templates first; the remaining checks follow.
390 if (NewTemplate &&
391 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
392 OldTemplate->getTemplateParameters(),
393 false, TPL_TemplateMatch) ||
394 OldType->getResultType() != NewType->getResultType()))
395 return true;
396
397 // If the function is a class member, its signature includes the
398 // cv-qualifiers (if any) on the function itself.
399 //
400 // As part of this, also check whether one of the member functions
401 // is static, in which case they are not overloads (C++
402 // 13.1p2). While not part of the definition of the signature,
403 // this check is important to determine whether these functions
404 // can be overloaded.
405 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
406 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
407 if (OldMethod && NewMethod &&
408 !OldMethod->isStatic() && !NewMethod->isStatic() &&
409 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
410 return true;
411
412 // The signatures match; this is not an overload.
413 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000414}
415
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000416/// TryImplicitConversion - Attempt to perform an implicit conversion
417/// from the given expression (Expr) to the given type (ToType). This
418/// function returns an implicit conversion sequence that can be used
419/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000420///
421/// void f(float f);
422/// void g(int i) { f(i); }
423///
424/// this routine would produce an implicit conversion sequence to
425/// describe the initialization of f from i, which will be a standard
426/// conversion sequence containing an lvalue-to-rvalue conversion (C++
427/// 4.1) followed by a floating-integral conversion (C++ 4.9).
428//
429/// Note that this routine only determines how the conversion can be
430/// performed; it does not actually perform the conversion. As such,
431/// it will not produce any diagnostics if no conversion is available,
432/// but will instead return an implicit conversion sequence of kind
433/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000439/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
440/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000441/// If @p UserCast, the implicit conversion is being done for a user-specified
442/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000443ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000444Sema::TryImplicitConversion(Expr* From, QualType ToType,
445 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000446 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000447 bool InOverloadResolution,
448 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000450 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000451 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000452 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
John McCall0d1da222010-01-12 00:44:57 +0000453 ICS.setStandard();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000454 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000455 (UserDefResult = IsUserDefinedConversion(From, ToType,
456 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000457 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000458 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000459 ForceRValue, UserCast)) == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000460 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000461 // C++ [over.ics.user]p4:
462 // A conversion of an expression of class type to the same class
463 // type is given Exact Match rank, and a conversion of an
464 // expression of class type to a base class of that type is
465 // given Conversion rank, in spite of the fact that a copy
466 // constructor (i.e., a user-defined conversion function) is
467 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000468 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000469 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000470 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000471 = Context.getCanonicalType(From->getType().getUnqualifiedType());
472 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000473 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000474 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000475 // Turn this into a "standard" conversion sequence, so that it
476 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000477 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000478 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000479 ICS.Standard.setFromType(From->getType());
480 ICS.Standard.setToType(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000481 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000482 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000483 ICS.Standard.Second = ICK_Derived_To_Base;
484 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000485 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000486
487 // C++ [over.best.ics]p4:
488 // However, when considering the argument of a user-defined
489 // conversion function that is a candidate by 13.3.1.3 when
490 // invoked for the copying of the temporary in the second step
491 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
492 // 13.3.1.6 in all cases, only standard conversion sequences and
493 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000494 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall0d1da222010-01-12 00:44:57 +0000495 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000496 ICS.Bad.init(BadConversionSequence::suppressed_user, From, ToType);
497 }
John McCalle8c8cd22010-01-13 22:30:33 +0000498 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000499 ICS.setAmbiguous();
500 ICS.Ambiguous.setFromType(From->getType());
501 ICS.Ambiguous.setToType(ToType);
502 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
503 Cand != Conversions.end(); ++Cand)
504 if (Cand->Viable)
505 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000506 } else {
John McCall0d1da222010-01-12 00:44:57 +0000507 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000508 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000509 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000510
511 return ICS;
512}
513
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000514/// \brief Determine whether the conversion from FromType to ToType is a valid
515/// conversion that strips "noreturn" off the nested function type.
516static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
517 QualType ToType, QualType &ResultTy) {
518 if (Context.hasSameUnqualifiedType(FromType, ToType))
519 return false;
520
521 // Strip the noreturn off the type we're converting from; noreturn can
522 // safely be removed.
523 FromType = Context.getNoReturnType(FromType, false);
524 if (!Context.hasSameUnqualifiedType(FromType, ToType))
525 return false;
526
527 ResultTy = FromType;
528 return true;
529}
530
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000531/// IsStandardConversion - Determines whether there is a standard
532/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
533/// expression From to the type ToType. Standard conversion sequences
534/// only consider non-class types; for conversions that involve class
535/// types, use TryImplicitConversion. If a conversion exists, SCS will
536/// contain the standard conversion sequence required to perform this
537/// conversion and this routine will return true. Otherwise, this
538/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000539bool
540Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000541 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000542 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000543 QualType FromType = From->getType();
544
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000545 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000546 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000547 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000548 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000549 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000550 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000552 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000553 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000554 if (FromType->isRecordType() || ToType->isRecordType()) {
555 if (getLangOptions().CPlusPlus)
556 return false;
557
Mike Stump11289f42009-09-09 15:08:12 +0000558 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000559 }
560
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000561 // The first conversion can be an lvalue-to-rvalue conversion,
562 // array-to-pointer conversion, or function-to-pointer conversion
563 // (C++ 4p1).
564
Mike Stump11289f42009-09-09 15:08:12 +0000565 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000566 // An lvalue (3.10) of a non-function, non-array type T can be
567 // converted to an rvalue.
568 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000569 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000570 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000571 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000572 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000573
574 // If T is a non-class type, the type of the rvalue is the
575 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000576 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
577 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000578 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000579 } else if (FromType->isArrayType()) {
580 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000581 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000582
583 // An lvalue or rvalue of type "array of N T" or "array of unknown
584 // bound of T" can be converted to an rvalue of type "pointer to
585 // T" (C++ 4.2p1).
586 FromType = Context.getArrayDecayedType(FromType);
587
588 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
589 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000590 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000591
592 // For the purpose of ranking in overload resolution
593 // (13.3.3.1.1), this conversion is considered an
594 // array-to-pointer conversion followed by a qualification
595 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000596 SCS.Second = ICK_Identity;
597 SCS.Third = ICK_Qualification;
John McCall0d1da222010-01-12 00:44:57 +0000598 SCS.setToType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000599 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000600 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000601 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
602 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000603 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000604
605 // An lvalue of function type T can be converted to an rvalue of
606 // type "pointer to T." The result is a pointer to the
607 // function. (C++ 4.3p1).
608 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000609 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000610 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000611 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000612 SCS.First = ICK_Function_To_Pointer;
613
614 // We were able to resolve the address of the overloaded function,
615 // so we can convert to the type of that function.
616 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000617 if (ToType->isLValueReferenceType())
618 FromType = Context.getLValueReferenceType(FromType);
619 else if (ToType->isRValueReferenceType())
620 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000621 else if (ToType->isMemberPointerType()) {
622 // Resolve address only succeeds if both sides are member pointers,
623 // but it doesn't have to be the same class. See DR 247.
624 // Note that this means that the type of &Derived::fn can be
625 // Ret (Base::*)(Args) if the fn overload actually found is from the
626 // base class, even if it was brought into the derived class via a
627 // using declaration. The standard isn't clear on this issue at all.
628 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
629 FromType = Context.getMemberPointerType(FromType,
630 Context.getTypeDeclType(M->getParent()).getTypePtr());
631 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000632 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000633 } else {
634 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000635 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000636 }
637
638 // The second conversion can be an integral promotion, floating
639 // point promotion, integral conversion, floating point conversion,
640 // floating-integral conversion, pointer conversion,
641 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000642 // For overloading in C, this can also be a "compatible-type"
643 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000644 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000645 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000646 // The unqualified versions of the types are the same: there's no
647 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000648 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000649 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000650 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000651 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000652 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000653 } else if (IsFloatingPointPromotion(FromType, ToType)) {
654 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000655 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000656 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000657 } else if (IsComplexPromotion(FromType, ToType)) {
658 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000659 SCS.Second = ICK_Complex_Promotion;
660 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000661 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000662 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000663 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000664 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000665 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000666 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
667 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000668 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000669 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000670 } else if (FromType->isComplexType() && ToType->isComplexType()) {
671 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000672 SCS.Second = ICK_Complex_Conversion;
673 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000674 } else if ((FromType->isFloatingType() &&
675 ToType->isIntegralType() && (!ToType->isBooleanType() &&
676 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000677 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000678 ToType->isFloatingType())) {
679 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000680 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000681 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000682 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
683 (ToType->isComplexType() && FromType->isArithmeticType())) {
684 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000685 SCS.Second = ICK_Complex_Real;
686 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000687 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
688 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000689 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000690 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000691 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000692 } else if (IsMemberPointerConversion(From, FromType, ToType,
693 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000694 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000695 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000696 } else if (ToType->isBooleanType() &&
697 (FromType->isArithmeticType() ||
698 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000699 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000700 FromType->isBlockPointerType() ||
701 FromType->isMemberPointerType() ||
702 FromType->isNullPtrType())) {
703 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000704 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000705 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000706 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000707 Context.typesAreCompatible(ToType, FromType)) {
708 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000709 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000710 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
711 // Treat a conversion that strips "noreturn" as an identity conversion.
712 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000713 } else {
714 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000715 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000716 }
717
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000718 QualType CanonFrom;
719 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000720 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000721 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000722 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000723 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000724 CanonFrom = Context.getCanonicalType(FromType);
725 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000726 } else {
727 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000728 SCS.Third = ICK_Identity;
729
Mike Stump11289f42009-09-09 15:08:12 +0000730 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000731 // [...] Any difference in top-level cv-qualification is
732 // subsumed by the initialization itself and does not constitute
733 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000734 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000735 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000736 if (CanonFrom.getLocalUnqualifiedType()
737 == CanonTo.getLocalUnqualifiedType() &&
738 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000739 FromType = ToType;
740 CanonFrom = CanonTo;
741 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000742 }
743
744 // If we have not converted the argument type to the parameter type,
745 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000746 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000747 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000748
John McCall0d1da222010-01-12 00:44:57 +0000749 SCS.setToType(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000750 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000751}
752
753/// IsIntegralPromotion - Determines whether the conversion from the
754/// expression From (whose potentially-adjusted type is FromType) to
755/// ToType is an integral promotion (C++ 4.5). If so, returns true and
756/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000757bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000758 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000759 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000760 if (!To) {
761 return false;
762 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000763
764 // An rvalue of type char, signed char, unsigned char, short int, or
765 // unsigned short int can be converted to an rvalue of type int if
766 // int can represent all the values of the source type; otherwise,
767 // the source rvalue can be converted to an rvalue of type unsigned
768 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000769 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000770 if (// We can promote any signed, promotable integer type to an int
771 (FromType->isSignedIntegerType() ||
772 // We can promote any unsigned integer type whose size is
773 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000774 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000775 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000776 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000777 }
778
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000779 return To->getKind() == BuiltinType::UInt;
780 }
781
782 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
783 // can be converted to an rvalue of the first of the following types
784 // that can represent all the values of its underlying type: int,
785 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000786
787 // We pre-calculate the promotion type for enum types.
788 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
789 if (ToType->isIntegerType())
790 return Context.hasSameUnqualifiedType(ToType,
791 FromEnumType->getDecl()->getPromotionType());
792
793 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000794 // Determine whether the type we're converting from is signed or
795 // unsigned.
796 bool FromIsSigned;
797 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000798
799 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
800 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000801
802 // The types we'll try to promote to, in the appropriate
803 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000804 QualType PromoteTypes[6] = {
805 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000806 Context.LongTy, Context.UnsignedLongTy ,
807 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000808 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000809 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000810 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
811 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000812 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000813 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
814 // We found the type that we can promote to. If this is the
815 // type we wanted, we have a promotion. Otherwise, no
816 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000817 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000818 }
819 }
820 }
821
822 // An rvalue for an integral bit-field (9.6) can be converted to an
823 // rvalue of type int if int can represent all the values of the
824 // bit-field; otherwise, it can be converted to unsigned int if
825 // unsigned int can represent all the values of the bit-field. If
826 // the bit-field is larger yet, no integral promotion applies to
827 // it. If the bit-field has an enumerated type, it is treated as any
828 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000829 // FIXME: We should delay checking of bit-fields until we actually perform the
830 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000831 using llvm::APSInt;
832 if (From)
833 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000834 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000835 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
836 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
837 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
838 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000839
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000840 // Are we promoting to an int from a bitfield that fits in an int?
841 if (BitWidth < ToSize ||
842 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
843 return To->getKind() == BuiltinType::Int;
844 }
Mike Stump11289f42009-09-09 15:08:12 +0000845
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000846 // Are we promoting to an unsigned int from an unsigned bitfield
847 // that fits into an unsigned int?
848 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
849 return To->getKind() == BuiltinType::UInt;
850 }
Mike Stump11289f42009-09-09 15:08:12 +0000851
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000852 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000853 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000854 }
Mike Stump11289f42009-09-09 15:08:12 +0000855
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000856 // An rvalue of type bool can be converted to an rvalue of type int,
857 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000858 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000859 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000860 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000861
862 return false;
863}
864
865/// IsFloatingPointPromotion - Determines whether the conversion from
866/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
867/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000868bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869 /// An rvalue of type float can be converted to an rvalue of type
870 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000871 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
872 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000873 if (FromBuiltin->getKind() == BuiltinType::Float &&
874 ToBuiltin->getKind() == BuiltinType::Double)
875 return true;
876
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000877 // C99 6.3.1.5p1:
878 // When a float is promoted to double or long double, or a
879 // double is promoted to long double [...].
880 if (!getLangOptions().CPlusPlus &&
881 (FromBuiltin->getKind() == BuiltinType::Float ||
882 FromBuiltin->getKind() == BuiltinType::Double) &&
883 (ToBuiltin->getKind() == BuiltinType::LongDouble))
884 return true;
885 }
886
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000887 return false;
888}
889
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000890/// \brief Determine if a conversion is a complex promotion.
891///
892/// A complex promotion is defined as a complex -> complex conversion
893/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000894/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000895bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000896 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000897 if (!FromComplex)
898 return false;
899
John McCall9dd450b2009-09-21 23:43:11 +0000900 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000901 if (!ToComplex)
902 return false;
903
904 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000905 ToComplex->getElementType()) ||
906 IsIntegralPromotion(0, FromComplex->getElementType(),
907 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000908}
909
Douglas Gregor237f96c2008-11-26 23:31:11 +0000910/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
911/// the pointer type FromPtr to a pointer to type ToPointee, with the
912/// same type qualifiers as FromPtr has on its pointee type. ToType,
913/// if non-empty, will be a pointer to ToType that may or may not have
914/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000915static QualType
916BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000917 QualType ToPointee, QualType ToType,
918 ASTContext &Context) {
919 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
920 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000921 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000922
923 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000924 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000925 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000926 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000927 return ToType;
928
929 // Build a pointer to ToPointee. It has the right qualifiers
930 // already.
931 return Context.getPointerType(ToPointee);
932 }
933
934 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000935 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000936 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
937 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000938}
939
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000940/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
941/// the FromType, which is an objective-c pointer, to ToType, which may or may
942/// not have the right set of qualifiers.
943static QualType
944BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
945 QualType ToType,
946 ASTContext &Context) {
947 QualType CanonFromType = Context.getCanonicalType(FromType);
948 QualType CanonToType = Context.getCanonicalType(ToType);
949 Qualifiers Quals = CanonFromType.getQualifiers();
950
951 // Exact qualifier match -> return the pointer type we're converting to.
952 if (CanonToType.getLocalQualifiers() == Quals)
953 return ToType;
954
955 // Just build a canonical type that has the right qualifiers.
956 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
957}
958
Mike Stump11289f42009-09-09 15:08:12 +0000959static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000960 bool InOverloadResolution,
961 ASTContext &Context) {
962 // Handle value-dependent integral null pointer constants correctly.
963 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
964 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
965 Expr->getType()->isIntegralType())
966 return !InOverloadResolution;
967
Douglas Gregor56751b52009-09-25 04:25:58 +0000968 return Expr->isNullPointerConstant(Context,
969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
970 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000971}
Mike Stump11289f42009-09-09 15:08:12 +0000972
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000973/// IsPointerConversion - Determines whether the conversion of the
974/// expression From, which has the (possibly adjusted) type FromType,
975/// can be converted to the type ToType via a pointer conversion (C++
976/// 4.10). If so, returns true and places the converted type (that
977/// might differ from ToType in its cv-qualifiers at some level) into
978/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000979///
Douglas Gregora29dc052008-11-27 01:19:21 +0000980/// This routine also supports conversions to and from block pointers
981/// and conversions with Objective-C's 'id', 'id<protocols...>', and
982/// pointers to interfaces. FIXME: Once we've determined the
983/// appropriate overloading rules for Objective-C, we may want to
984/// split the Objective-C checks into a different routine; however,
985/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000986/// conversions, so for now they live here. IncompatibleObjC will be
987/// set if the conversion is an allowed Objective-C conversion that
988/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000989bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000990 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000991 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000992 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000993 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000994 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
995 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000996
Mike Stump11289f42009-09-09 15:08:12 +0000997 // Conversion from a null pointer constant to any Objective-C pointer type.
998 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001000 ConvertedType = ToType;
1001 return true;
1002 }
1003
Douglas Gregor231d1c62008-11-27 00:15:41 +00001004 // Blocks: Block pointers can be converted to void*.
1005 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001006 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001007 ConvertedType = ToType;
1008 return true;
1009 }
1010 // Blocks: A null pointer constant can be converted to a block
1011 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001012 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001014 ConvertedType = ToType;
1015 return true;
1016 }
1017
Sebastian Redl576fd422009-05-10 18:38:11 +00001018 // If the left-hand-side is nullptr_t, the right side can be a null
1019 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001020 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001026 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027 if (!ToTypePtr)
1028 return false;
1029
1030 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001031 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001032 ConvertedType = ToType;
1033 return true;
1034 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001035
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001036 // Beyond this point, both types need to be pointers
1037 // , including objective-c pointers.
1038 QualType ToPointeeType = ToTypePtr->getPointeeType();
1039 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1040 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1041 ToType, Context);
1042 return true;
1043
1044 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001045 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001046 if (!FromTypePtr)
1047 return false;
1048
1049 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001050
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001051 // An rvalue of type "pointer to cv T," where T is an object type,
1052 // can be converted to an rvalue of type "pointer to cv void" (C++
1053 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001054 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001056 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001057 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001058 return true;
1059 }
1060
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001061 // When we're overloading in C, we allow a special kind of pointer
1062 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001063 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001064 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001065 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001066 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001067 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001068 return true;
1069 }
1070
Douglas Gregor5c407d92008-10-23 00:40:37 +00001071 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001072 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001073 // An rvalue of type "pointer to cv D," where D is a class type,
1074 // can be converted to an rvalue of type "pointer to cv B," where
1075 // B is a base class (clause 10) of D. If B is an inaccessible
1076 // (clause 11) or ambiguous (10.2) base class of D, a program that
1077 // necessitates this conversion is ill-formed. The result of the
1078 // conversion is a pointer to the base class sub-object of the
1079 // derived class object. The null pointer value is converted to
1080 // the null pointer value of the destination type.
1081 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001082 // Note that we do not check for ambiguity or inaccessibility
1083 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001084 if (getLangOptions().CPlusPlus &&
1085 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001086 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001087 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001088 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001089 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001090 ToType, Context);
1091 return true;
1092 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001093
Douglas Gregora119f102008-12-19 19:13:09 +00001094 return false;
1095}
1096
1097/// isObjCPointerConversion - Determines whether this is an
1098/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1099/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001100bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001101 QualType& ConvertedType,
1102 bool &IncompatibleObjC) {
1103 if (!getLangOptions().ObjC1)
1104 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001105
Steve Naroff7cae42b2009-07-10 23:34:53 +00001106 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001107 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001108 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001109 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001110
Steve Naroff7cae42b2009-07-10 23:34:53 +00001111 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001112 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001113 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001114 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001115 ConvertedType = ToType;
1116 return true;
1117 }
1118 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001119 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001120 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001121 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001122 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001123 ConvertedType = ToType;
1124 return true;
1125 }
1126 // Objective C++: We're able to convert from a pointer to an
1127 // interface to a pointer to a different interface.
1128 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1129 ConvertedType = ToType;
1130 return true;
1131 }
1132
1133 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1134 // Okay: this is some kind of implicit downcast of Objective-C
1135 // interfaces, which is permitted. However, we're going to
1136 // complain about it.
1137 IncompatibleObjC = true;
1138 ConvertedType = FromType;
1139 return true;
1140 }
Mike Stump11289f42009-09-09 15:08:12 +00001141 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001142 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001143 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001144 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001145 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001146 else if (const BlockPointerType *ToBlockPtr =
1147 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001148 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001149 // to a block pointer type.
1150 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1151 ConvertedType = ToType;
1152 return true;
1153 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001154 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001155 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001156 else if (FromType->getAs<BlockPointerType>() &&
1157 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1158 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001159 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001160 ConvertedType = ToType;
1161 return true;
1162 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001163 else
Douglas Gregora119f102008-12-19 19:13:09 +00001164 return false;
1165
Douglas Gregor033f56d2008-12-23 00:53:59 +00001166 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001167 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001168 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001169 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001170 FromPointeeType = FromBlockPtr->getPointeeType();
1171 else
Douglas Gregora119f102008-12-19 19:13:09 +00001172 return false;
1173
Douglas Gregora119f102008-12-19 19:13:09 +00001174 // If we have pointers to pointers, recursively check whether this
1175 // is an Objective-C conversion.
1176 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1177 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1178 IncompatibleObjC)) {
1179 // We always complain about this conversion.
1180 IncompatibleObjC = true;
1181 ConvertedType = ToType;
1182 return true;
1183 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001184 // Allow conversion of pointee being objective-c pointer to another one;
1185 // as in I* to id.
1186 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1187 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1188 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1189 IncompatibleObjC)) {
1190 ConvertedType = ToType;
1191 return true;
1192 }
1193
Douglas Gregor033f56d2008-12-23 00:53:59 +00001194 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001195 // differences in the argument and result types are in Objective-C
1196 // pointer conversions. If so, we permit the conversion (but
1197 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001198 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001199 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001200 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001201 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001202 if (FromFunctionType && ToFunctionType) {
1203 // If the function types are exactly the same, this isn't an
1204 // Objective-C pointer conversion.
1205 if (Context.getCanonicalType(FromPointeeType)
1206 == Context.getCanonicalType(ToPointeeType))
1207 return false;
1208
1209 // Perform the quick checks that will tell us whether these
1210 // function types are obviously different.
1211 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1212 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1213 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1214 return false;
1215
1216 bool HasObjCConversion = false;
1217 if (Context.getCanonicalType(FromFunctionType->getResultType())
1218 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1219 // Okay, the types match exactly. Nothing to do.
1220 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1221 ToFunctionType->getResultType(),
1222 ConvertedType, IncompatibleObjC)) {
1223 // Okay, we have an Objective-C pointer conversion.
1224 HasObjCConversion = true;
1225 } else {
1226 // Function types are too different. Abort.
1227 return false;
1228 }
Mike Stump11289f42009-09-09 15:08:12 +00001229
Douglas Gregora119f102008-12-19 19:13:09 +00001230 // Check argument types.
1231 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1232 ArgIdx != NumArgs; ++ArgIdx) {
1233 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1234 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1235 if (Context.getCanonicalType(FromArgType)
1236 == Context.getCanonicalType(ToArgType)) {
1237 // Okay, the types match exactly. Nothing to do.
1238 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1239 ConvertedType, IncompatibleObjC)) {
1240 // Okay, we have an Objective-C pointer conversion.
1241 HasObjCConversion = true;
1242 } else {
1243 // Argument types are too different. Abort.
1244 return false;
1245 }
1246 }
1247
1248 if (HasObjCConversion) {
1249 // We had an Objective-C conversion. Allow this pointer
1250 // conversion, but complain about it.
1251 ConvertedType = ToType;
1252 IncompatibleObjC = true;
1253 return true;
1254 }
1255 }
1256
Sebastian Redl72b597d2009-01-25 19:43:20 +00001257 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258}
1259
Douglas Gregor39c16d42008-10-24 04:54:22 +00001260/// CheckPointerConversion - Check the pointer conversion from the
1261/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001262/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001263/// conversions for which IsPointerConversion has already returned
1264/// true. It returns true and produces a diagnostic if there was an
1265/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001266bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001267 CastExpr::CastKind &Kind,
1268 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001269 QualType FromType = From->getType();
1270
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001271 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1272 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001273 QualType FromPointeeType = FromPtrType->getPointeeType(),
1274 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001275
Douglas Gregor39c16d42008-10-24 04:54:22 +00001276 if (FromPointeeType->isRecordType() &&
1277 ToPointeeType->isRecordType()) {
1278 // We must have a derived-to-base conversion. Check an
1279 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001280 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1281 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001282 From->getSourceRange(),
1283 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001284 return true;
1285
1286 // The conversion was successful.
1287 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001288 }
1289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001291 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001292 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001293 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001294 // Objective-C++ conversions are always okay.
1295 // FIXME: We should have a different class of conversions for the
1296 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001297 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001298 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001299
Steve Naroff7cae42b2009-07-10 23:34:53 +00001300 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001301 return false;
1302}
1303
Sebastian Redl72b597d2009-01-25 19:43:20 +00001304/// IsMemberPointerConversion - Determines whether the conversion of the
1305/// expression From, which has the (possibly adjusted) type FromType, can be
1306/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1307/// If so, returns true and places the converted type (that might differ from
1308/// ToType in its cv-qualifiers at some level) into ConvertedType.
1309bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001310 QualType ToType,
1311 bool InOverloadResolution,
1312 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001313 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001314 if (!ToTypePtr)
1315 return false;
1316
1317 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001318 if (From->isNullPointerConstant(Context,
1319 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1320 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001321 ConvertedType = ToType;
1322 return true;
1323 }
1324
1325 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001326 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001327 if (!FromTypePtr)
1328 return false;
1329
1330 // A pointer to member of B can be converted to a pointer to member of D,
1331 // where D is derived from B (C++ 4.11p2).
1332 QualType FromClass(FromTypePtr->getClass(), 0);
1333 QualType ToClass(ToTypePtr->getClass(), 0);
1334 // FIXME: What happens when these are dependent? Is this function even called?
1335
1336 if (IsDerivedFrom(ToClass, FromClass)) {
1337 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1338 ToClass.getTypePtr());
1339 return true;
1340 }
1341
1342 return false;
1343}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001344
Sebastian Redl72b597d2009-01-25 19:43:20 +00001345/// CheckMemberPointerConversion - Check the member pointer conversion from the
1346/// expression From to the type ToType. This routine checks for ambiguous or
1347/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1348/// for which IsMemberPointerConversion has already returned true. It returns
1349/// true and produces a diagnostic if there was an error, or returns false
1350/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001351bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001352 CastExpr::CastKind &Kind,
1353 bool IgnoreBaseAccess) {
1354 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001355 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001356 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001357 if (!FromPtrType) {
1358 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001359 assert(From->isNullPointerConstant(Context,
1360 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001361 "Expr must be null pointer constant!");
1362 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001363 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001364 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001365
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001367 assert(ToPtrType && "No member pointer cast has a target type "
1368 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001369
Sebastian Redled8f2002009-01-28 18:33:18 +00001370 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1371 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001372
Sebastian Redled8f2002009-01-28 18:33:18 +00001373 // FIXME: What about dependent types?
1374 assert(FromClass->isRecordType() && "Pointer into non-class.");
1375 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001376
Douglas Gregor36d1b142009-10-06 17:59:45 +00001377 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1378 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001379 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1380 assert(DerivationOkay &&
1381 "Should not have been called if derivation isn't OK.");
1382 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001383
Sebastian Redled8f2002009-01-28 18:33:18 +00001384 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1385 getUnqualifiedType())) {
1386 // Derivation is ambiguous. Redo the check to find the exact paths.
1387 Paths.clear();
1388 Paths.setRecordingPaths(true);
1389 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1390 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1391 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001392
Sebastian Redled8f2002009-01-28 18:33:18 +00001393 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1394 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1395 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1396 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001397 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001398
Douglas Gregor89ee6822009-02-28 01:32:25 +00001399 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001400 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1401 << FromClass << ToClass << QualType(VBase, 0)
1402 << From->getSourceRange();
1403 return true;
1404 }
1405
Anders Carlssond7923c62009-08-22 23:33:40 +00001406 // Must be a base to derived member conversion.
1407 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001408 return false;
1409}
1410
Douglas Gregor9a657932008-10-21 23:43:52 +00001411/// IsQualificationConversion - Determines whether the conversion from
1412/// an rvalue of type FromType to ToType is a qualification conversion
1413/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001414bool
1415Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001416 FromType = Context.getCanonicalType(FromType);
1417 ToType = Context.getCanonicalType(ToType);
1418
1419 // If FromType and ToType are the same type, this is not a
1420 // qualification conversion.
1421 if (FromType == ToType)
1422 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001423
Douglas Gregor9a657932008-10-21 23:43:52 +00001424 // (C++ 4.4p4):
1425 // A conversion can add cv-qualifiers at levels other than the first
1426 // in multi-level pointers, subject to the following rules: [...]
1427 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001428 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001429 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001430 // Within each iteration of the loop, we check the qualifiers to
1431 // determine if this still looks like a qualification
1432 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001433 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001434 // until there are no more pointers or pointers-to-members left to
1435 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001436 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001437
1438 // -- for every j > 0, if const is in cv 1,j then const is in cv
1439 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001440 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001441 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregor9a657932008-10-21 23:43:52 +00001443 // -- if the cv 1,j and cv 2,j are different, then const is in
1444 // every cv for 0 < k < j.
1445 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001446 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001447 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001448
Douglas Gregor9a657932008-10-21 23:43:52 +00001449 // Keep track of whether all prior cv-qualifiers in the "to" type
1450 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001451 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001452 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001453 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001454
1455 // We are left with FromType and ToType being the pointee types
1456 // after unwrapping the original FromType and ToType the same number
1457 // of types. If we unwrapped any pointers, and if FromType and
1458 // ToType have the same unqualified type (since we checked
1459 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001460 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001461}
1462
Douglas Gregor576e98c2009-01-30 23:27:23 +00001463/// Determines whether there is a user-defined conversion sequence
1464/// (C++ [over.ics.user]) that converts expression From to the type
1465/// ToType. If such a conversion exists, User will contain the
1466/// user-defined conversion sequence that performs such a conversion
1467/// and this routine will return true. Otherwise, this routine returns
1468/// false and User is unspecified.
1469///
1470/// \param AllowConversionFunctions true if the conversion should
1471/// consider conversion functions at all. If false, only constructors
1472/// will be considered.
1473///
1474/// \param AllowExplicit true if the conversion should consider C++0x
1475/// "explicit" conversion functions as well as non-explicit conversion
1476/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001477///
1478/// \param ForceRValue true if the expression should be treated as an rvalue
1479/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001480/// \param UserCast true if looking for user defined conversion for a static
1481/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001482OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1483 UserDefinedConversionSequence& User,
1484 OverloadCandidateSet& CandidateSet,
1485 bool AllowConversionFunctions,
1486 bool AllowExplicit,
1487 bool ForceRValue,
1488 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001489 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001490 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1491 // We're not going to find any constructors.
1492 } else if (CXXRecordDecl *ToRecordDecl
1493 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001494 // C++ [over.match.ctor]p1:
1495 // When objects of class type are direct-initialized (8.5), or
1496 // copy-initialized from an expression of the same or a
1497 // derived class type (8.5), overload resolution selects the
1498 // constructor. [...] For copy-initialization, the candidate
1499 // functions are all the converting constructors (12.3.1) of
1500 // that class. The argument list is the expression-list within
1501 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001502 bool SuppressUserConversions = !UserCast;
1503 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1504 IsDerivedFrom(From->getType(), ToType)) {
1505 SuppressUserConversions = false;
1506 AllowConversionFunctions = false;
1507 }
1508
Mike Stump11289f42009-09-09 15:08:12 +00001509 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001510 = Context.DeclarationNames.getCXXConstructorName(
1511 Context.getCanonicalType(ToType).getUnqualifiedType());
1512 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001513 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001514 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001515 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001516 // Find the constructor (which may be a template).
1517 CXXConstructorDecl *Constructor = 0;
1518 FunctionTemplateDecl *ConstructorTmpl
1519 = dyn_cast<FunctionTemplateDecl>(*Con);
1520 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001521 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001522 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1523 else
1524 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001525
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001526 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001527 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001528 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001529 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1530 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001531 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001532 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001533 // Allow one user-defined conversion when user specifies a
1534 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001535 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001536 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001537 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001538 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539 }
1540 }
1541
Douglas Gregor576e98c2009-01-30 23:27:23 +00001542 if (!AllowConversionFunctions) {
1543 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001544 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1545 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001546 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001547 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001548 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001549 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001550 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001551 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1552 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001553 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001554 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001555 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001556 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001557 NamedDecl *D = *I;
1558 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1559 if (isa<UsingShadowDecl>(D))
1560 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1561
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001562 CXXConversionDecl *Conv;
1563 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001564 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001565 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1566 else
John McCalld14a8642009-11-21 08:51:07 +00001567 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001568
1569 if (AllowExplicit || !Conv->isExplicit()) {
1570 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001571 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1572 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001573 else
John McCall6e9f8f62009-12-03 04:06:58 +00001574 AddConversionCandidate(Conv, ActingContext, From, ToType,
1575 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001576 }
1577 }
1578 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001579 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001580
1581 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001582 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001583 case OR_Success:
1584 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001585 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1587 // C++ [over.ics.user]p1:
1588 // If the user-defined conversion is specified by a
1589 // constructor (12.3.1), the initial standard conversion
1590 // sequence converts the source type to the type required by
1591 // the argument of the constructor.
1592 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001593 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001594 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001595 User.EllipsisConversion = true;
1596 else {
1597 User.Before = Best->Conversions[0].Standard;
1598 User.EllipsisConversion = false;
1599 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001600 User.ConversionFunction = Constructor;
1601 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001602 User.After.setFromType(
1603 ThisType->getAs<PointerType>()->getPointeeType());
1604 User.After.setToType(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001605 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001606 } else if (CXXConversionDecl *Conversion
1607 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1608 // C++ [over.ics.user]p1:
1609 //
1610 // [...] If the user-defined conversion is specified by a
1611 // conversion function (12.3.2), the initial standard
1612 // conversion sequence converts the source type to the
1613 // implicit object parameter of the conversion function.
1614 User.Before = Best->Conversions[0].Standard;
1615 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001616 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001617
1618 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001619 // The second standard conversion sequence converts the
1620 // result of the user-defined conversion to the target type
1621 // for the sequence. Since an implicit conversion sequence
1622 // is an initialization, the special rules for
1623 // initialization by user-defined conversion apply when
1624 // selecting the best user-defined conversion for a
1625 // user-defined conversion sequence (see 13.3.3 and
1626 // 13.3.3.1).
1627 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001628 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001629 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001630 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001631 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001632 }
Mike Stump11289f42009-09-09 15:08:12 +00001633
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001634 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001635 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001636 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001637 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001638 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001639
1640 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001641 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001642 }
1643
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001644 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001646
1647bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001648Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001649 ImplicitConversionSequence ICS;
1650 OverloadCandidateSet CandidateSet;
1651 OverloadingResult OvResult =
1652 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1653 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001654 if (OvResult == OR_Ambiguous)
1655 Diag(From->getSourceRange().getBegin(),
1656 diag::err_typecheck_ambiguous_condition)
1657 << From->getType() << ToType << From->getSourceRange();
1658 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1659 Diag(From->getSourceRange().getBegin(),
1660 diag::err_typecheck_nonviable_condition)
1661 << From->getType() << ToType << From->getSourceRange();
1662 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001663 return false;
John McCallad907772010-01-12 07:18:19 +00001664 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001665 return true;
1666}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001667
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668/// CompareImplicitConversionSequences - Compare two implicit
1669/// conversion sequences to determine whether one is better than the
1670/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001671ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1673 const ImplicitConversionSequence& ICS2)
1674{
1675 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1676 // conversion sequences (as defined in 13.3.3.1)
1677 // -- a standard conversion sequence (13.3.3.1.1) is a better
1678 // conversion sequence than a user-defined conversion sequence or
1679 // an ellipsis conversion sequence, and
1680 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1681 // conversion sequence than an ellipsis conversion sequence
1682 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001683 //
John McCall0d1da222010-01-12 00:44:57 +00001684 // C++0x [over.best.ics]p10:
1685 // For the purpose of ranking implicit conversion sequences as
1686 // described in 13.3.3.2, the ambiguous conversion sequence is
1687 // treated as a user-defined sequence that is indistinguishable
1688 // from any other user-defined conversion sequence.
1689 if (ICS1.getKind() < ICS2.getKind()) {
1690 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1691 return ImplicitConversionSequence::Better;
1692 } else if (ICS2.getKind() < ICS1.getKind()) {
1693 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1694 return ImplicitConversionSequence::Worse;
1695 }
1696
1697 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1698 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699
1700 // Two implicit conversion sequences of the same form are
1701 // indistinguishable conversion sequences unless one of the
1702 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001703 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001705 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706 // User-defined conversion sequence U1 is a better conversion
1707 // sequence than another user-defined conversion sequence U2 if
1708 // they contain the same user-defined conversion function or
1709 // constructor and if the second standard conversion sequence of
1710 // U1 is better than the second standard conversion sequence of
1711 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001712 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 ICS2.UserDefined.ConversionFunction)
1714 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1715 ICS2.UserDefined.After);
1716 }
1717
1718 return ImplicitConversionSequence::Indistinguishable;
1719}
1720
1721/// CompareStandardConversionSequences - Compare two standard
1722/// conversion sequences to determine whether one is better than the
1723/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001724ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001725Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1726 const StandardConversionSequence& SCS2)
1727{
1728 // Standard conversion sequence S1 is a better conversion sequence
1729 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1730
1731 // -- S1 is a proper subsequence of S2 (comparing the conversion
1732 // sequences in the canonical form defined by 13.3.3.1.1,
1733 // excluding any Lvalue Transformation; the identity conversion
1734 // sequence is considered to be a subsequence of any
1735 // non-identity conversion sequence) or, if not that,
1736 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1737 // Neither is a proper subsequence of the other. Do nothing.
1738 ;
1739 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1740 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001741 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001742 SCS1.Third == ICK_Identity))
1743 // SCS1 is a proper subsequence of SCS2.
1744 return ImplicitConversionSequence::Better;
1745 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1746 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001747 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 SCS2.Third == ICK_Identity))
1749 // SCS2 is a proper subsequence of SCS1.
1750 return ImplicitConversionSequence::Worse;
1751
1752 // -- the rank of S1 is better than the rank of S2 (by the rules
1753 // defined below), or, if not that,
1754 ImplicitConversionRank Rank1 = SCS1.getRank();
1755 ImplicitConversionRank Rank2 = SCS2.getRank();
1756 if (Rank1 < Rank2)
1757 return ImplicitConversionSequence::Better;
1758 else if (Rank2 < Rank1)
1759 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001760
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001761 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1762 // are indistinguishable unless one of the following rules
1763 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001764
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001765 // A conversion that is not a conversion of a pointer, or
1766 // pointer to member, to bool is better than another conversion
1767 // that is such a conversion.
1768 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1769 return SCS2.isPointerConversionToBool()
1770 ? ImplicitConversionSequence::Better
1771 : ImplicitConversionSequence::Worse;
1772
Douglas Gregor5c407d92008-10-23 00:40:37 +00001773 // C++ [over.ics.rank]p4b2:
1774 //
1775 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001776 // conversion of B* to A* is better than conversion of B* to
1777 // void*, and conversion of A* to void* is better than conversion
1778 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001779 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001780 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001781 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001782 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001783 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1784 // Exactly one of the conversion sequences is a conversion to
1785 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001786 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1787 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001788 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1789 // Neither conversion sequence converts to a void pointer; compare
1790 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001791 if (ImplicitConversionSequence::CompareKind DerivedCK
1792 = CompareDerivedToBaseConversions(SCS1, SCS2))
1793 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001794 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1795 // Both conversion sequences are conversions to void
1796 // pointers. Compare the source types to determine if there's an
1797 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001798 QualType FromType1 = SCS1.getFromType();
1799 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001800
1801 // Adjust the types we're converting from via the array-to-pointer
1802 // conversion, if we need to.
1803 if (SCS1.First == ICK_Array_To_Pointer)
1804 FromType1 = Context.getArrayDecayedType(FromType1);
1805 if (SCS2.First == ICK_Array_To_Pointer)
1806 FromType2 = Context.getArrayDecayedType(FromType2);
1807
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001808 QualType FromPointee1
1809 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1810 QualType FromPointee2
1811 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001812
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001813 if (IsDerivedFrom(FromPointee2, FromPointee1))
1814 return ImplicitConversionSequence::Better;
1815 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1816 return ImplicitConversionSequence::Worse;
1817
1818 // Objective-C++: If one interface is more specific than the
1819 // other, it is the better one.
1820 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1821 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1822 if (FromIface1 && FromIface1) {
1823 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1824 return ImplicitConversionSequence::Better;
1825 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1826 return ImplicitConversionSequence::Worse;
1827 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001828 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001829
1830 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1831 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001832 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001833 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001834 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001835
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001836 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001837 // C++0x [over.ics.rank]p3b4:
1838 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1839 // implicit object parameter of a non-static member function declared
1840 // without a ref-qualifier, and S1 binds an rvalue reference to an
1841 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001842 // FIXME: We don't know if we're dealing with the implicit object parameter,
1843 // or if the member function in this case has a ref qualifier.
1844 // (Of course, we don't have ref qualifiers yet.)
1845 if (SCS1.RRefBinding != SCS2.RRefBinding)
1846 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1847 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001848
1849 // C++ [over.ics.rank]p3b4:
1850 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1851 // which the references refer are the same type except for
1852 // top-level cv-qualifiers, and the type to which the reference
1853 // initialized by S2 refers is more cv-qualified than the type
1854 // to which the reference initialized by S1 refers.
John McCall0d1da222010-01-12 00:44:57 +00001855 QualType T1 = SCS1.getToType();
1856 QualType T2 = SCS2.getToType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001857 T1 = Context.getCanonicalType(T1);
1858 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001859 Qualifiers T1Quals, T2Quals;
1860 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1861 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1862 if (UnqualT1 == UnqualT2) {
1863 // If the type is an array type, promote the element qualifiers to the type
1864 // for comparison.
1865 if (isa<ArrayType>(T1) && T1Quals)
1866 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1867 if (isa<ArrayType>(T2) && T2Quals)
1868 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001869 if (T2.isMoreQualifiedThan(T1))
1870 return ImplicitConversionSequence::Better;
1871 else if (T1.isMoreQualifiedThan(T2))
1872 return ImplicitConversionSequence::Worse;
1873 }
1874 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001875
1876 return ImplicitConversionSequence::Indistinguishable;
1877}
1878
1879/// CompareQualificationConversions - Compares two standard conversion
1880/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001881/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1882ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001883Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001884 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001885 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001886 // -- S1 and S2 differ only in their qualification conversion and
1887 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1888 // cv-qualification signature of type T1 is a proper subset of
1889 // the cv-qualification signature of type T2, and S1 is not the
1890 // deprecated string literal array-to-pointer conversion (4.2).
1891 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1892 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1893 return ImplicitConversionSequence::Indistinguishable;
1894
1895 // FIXME: the example in the standard doesn't use a qualification
1896 // conversion (!)
1897 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1898 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1899 T1 = Context.getCanonicalType(T1);
1900 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001901 Qualifiers T1Quals, T2Quals;
1902 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1903 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001904
1905 // If the types are the same, we won't learn anything by unwrapped
1906 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001907 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001908 return ImplicitConversionSequence::Indistinguishable;
1909
Chandler Carruth607f38e2009-12-29 07:16:59 +00001910 // If the type is an array type, promote the element qualifiers to the type
1911 // for comparison.
1912 if (isa<ArrayType>(T1) && T1Quals)
1913 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1914 if (isa<ArrayType>(T2) && T2Quals)
1915 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1916
Mike Stump11289f42009-09-09 15:08:12 +00001917 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001918 = ImplicitConversionSequence::Indistinguishable;
1919 while (UnwrapSimilarPointerTypes(T1, T2)) {
1920 // Within each iteration of the loop, we check the qualifiers to
1921 // determine if this still looks like a qualification
1922 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001923 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001924 // until there are no more pointers or pointers-to-members left
1925 // to unwrap. This essentially mimics what
1926 // IsQualificationConversion does, but here we're checking for a
1927 // strict subset of qualifiers.
1928 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1929 // The qualifiers are the same, so this doesn't tell us anything
1930 // about how the sequences rank.
1931 ;
1932 else if (T2.isMoreQualifiedThan(T1)) {
1933 // T1 has fewer qualifiers, so it could be the better sequence.
1934 if (Result == ImplicitConversionSequence::Worse)
1935 // Neither has qualifiers that are a subset of the other's
1936 // qualifiers.
1937 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001938
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001939 Result = ImplicitConversionSequence::Better;
1940 } else if (T1.isMoreQualifiedThan(T2)) {
1941 // T2 has fewer qualifiers, so it could be the better sequence.
1942 if (Result == ImplicitConversionSequence::Better)
1943 // Neither has qualifiers that are a subset of the other's
1944 // qualifiers.
1945 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001946
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001947 Result = ImplicitConversionSequence::Worse;
1948 } else {
1949 // Qualifiers are disjoint.
1950 return ImplicitConversionSequence::Indistinguishable;
1951 }
1952
1953 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001954 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001955 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001956 }
1957
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001958 // Check that the winning standard conversion sequence isn't using
1959 // the deprecated string literal array to pointer conversion.
1960 switch (Result) {
1961 case ImplicitConversionSequence::Better:
1962 if (SCS1.Deprecated)
1963 Result = ImplicitConversionSequence::Indistinguishable;
1964 break;
1965
1966 case ImplicitConversionSequence::Indistinguishable:
1967 break;
1968
1969 case ImplicitConversionSequence::Worse:
1970 if (SCS2.Deprecated)
1971 Result = ImplicitConversionSequence::Indistinguishable;
1972 break;
1973 }
1974
1975 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001976}
1977
Douglas Gregor5c407d92008-10-23 00:40:37 +00001978/// CompareDerivedToBaseConversions - Compares two standard conversion
1979/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001980/// various kinds of derived-to-base conversions (C++
1981/// [over.ics.rank]p4b3). As part of these checks, we also look at
1982/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001983ImplicitConversionSequence::CompareKind
1984Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1985 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00001986 QualType FromType1 = SCS1.getFromType();
1987 QualType ToType1 = SCS1.getToType();
1988 QualType FromType2 = SCS2.getFromType();
1989 QualType ToType2 = SCS2.getToType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001990
1991 // Adjust the types we're converting from via the array-to-pointer
1992 // conversion, if we need to.
1993 if (SCS1.First == ICK_Array_To_Pointer)
1994 FromType1 = Context.getArrayDecayedType(FromType1);
1995 if (SCS2.First == ICK_Array_To_Pointer)
1996 FromType2 = Context.getArrayDecayedType(FromType2);
1997
1998 // Canonicalize all of the types.
1999 FromType1 = Context.getCanonicalType(FromType1);
2000 ToType1 = Context.getCanonicalType(ToType1);
2001 FromType2 = Context.getCanonicalType(FromType2);
2002 ToType2 = Context.getCanonicalType(ToType2);
2003
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002004 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002005 //
2006 // If class B is derived directly or indirectly from class A and
2007 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002008 //
2009 // For Objective-C, we let A, B, and C also be Objective-C
2010 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002011
2012 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002013 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002014 SCS2.Second == ICK_Pointer_Conversion &&
2015 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2016 FromType1->isPointerType() && FromType2->isPointerType() &&
2017 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002018 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002019 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002020 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002021 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002022 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002023 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002024 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002025 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002026
John McCall9dd450b2009-09-21 23:43:11 +00002027 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2028 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2029 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2030 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002031
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002032 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002033 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2034 if (IsDerivedFrom(ToPointee1, ToPointee2))
2035 return ImplicitConversionSequence::Better;
2036 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2037 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002038
2039 if (ToIface1 && ToIface2) {
2040 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2041 return ImplicitConversionSequence::Better;
2042 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2043 return ImplicitConversionSequence::Worse;
2044 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002045 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002046
2047 // -- conversion of B* to A* is better than conversion of C* to A*,
2048 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2049 if (IsDerivedFrom(FromPointee2, FromPointee1))
2050 return ImplicitConversionSequence::Better;
2051 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2052 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002053
Douglas Gregor237f96c2008-11-26 23:31:11 +00002054 if (FromIface1 && FromIface2) {
2055 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2056 return ImplicitConversionSequence::Better;
2057 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2058 return ImplicitConversionSequence::Worse;
2059 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002060 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002061 }
2062
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002063 // Compare based on reference bindings.
2064 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2065 SCS1.Second == ICK_Derived_To_Base) {
2066 // -- binding of an expression of type C to a reference of type
2067 // B& is better than binding an expression of type C to a
2068 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002069 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2070 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002071 if (IsDerivedFrom(ToType1, ToType2))
2072 return ImplicitConversionSequence::Better;
2073 else if (IsDerivedFrom(ToType2, ToType1))
2074 return ImplicitConversionSequence::Worse;
2075 }
2076
Douglas Gregor2fe98832008-11-03 19:09:14 +00002077 // -- binding of an expression of type B to a reference of type
2078 // A& is better than binding an expression of type C to a
2079 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002080 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2081 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002082 if (IsDerivedFrom(FromType2, FromType1))
2083 return ImplicitConversionSequence::Better;
2084 else if (IsDerivedFrom(FromType1, FromType2))
2085 return ImplicitConversionSequence::Worse;
2086 }
2087 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002088
2089 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002090 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2091 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2092 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2093 const MemberPointerType * FromMemPointer1 =
2094 FromType1->getAs<MemberPointerType>();
2095 const MemberPointerType * ToMemPointer1 =
2096 ToType1->getAs<MemberPointerType>();
2097 const MemberPointerType * FromMemPointer2 =
2098 FromType2->getAs<MemberPointerType>();
2099 const MemberPointerType * ToMemPointer2 =
2100 ToType2->getAs<MemberPointerType>();
2101 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2102 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2103 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2104 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2105 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2106 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2107 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2108 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002109 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002110 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2111 if (IsDerivedFrom(ToPointee1, ToPointee2))
2112 return ImplicitConversionSequence::Worse;
2113 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2114 return ImplicitConversionSequence::Better;
2115 }
2116 // conversion of B::* to C::* is better than conversion of A::* to C::*
2117 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2118 if (IsDerivedFrom(FromPointee1, FromPointee2))
2119 return ImplicitConversionSequence::Better;
2120 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2121 return ImplicitConversionSequence::Worse;
2122 }
2123 }
2124
Douglas Gregor2fe98832008-11-03 19:09:14 +00002125 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2126 SCS1.Second == ICK_Derived_To_Base) {
2127 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002128 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2129 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002130 if (IsDerivedFrom(ToType1, ToType2))
2131 return ImplicitConversionSequence::Better;
2132 else if (IsDerivedFrom(ToType2, ToType1))
2133 return ImplicitConversionSequence::Worse;
2134 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002135
Douglas Gregor2fe98832008-11-03 19:09:14 +00002136 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002137 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2138 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002139 if (IsDerivedFrom(FromType2, FromType1))
2140 return ImplicitConversionSequence::Better;
2141 else if (IsDerivedFrom(FromType1, FromType2))
2142 return ImplicitConversionSequence::Worse;
2143 }
2144 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002145
Douglas Gregor5c407d92008-10-23 00:40:37 +00002146 return ImplicitConversionSequence::Indistinguishable;
2147}
2148
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002149/// TryCopyInitialization - Try to copy-initialize a value of type
2150/// ToType from the expression From. Return the implicit conversion
2151/// sequence required to pass this argument, which may be a bad
2152/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002153/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002154/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2155/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002156ImplicitConversionSequence
2157Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002158 bool SuppressUserConversions, bool ForceRValue,
2159 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002160 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002161 ImplicitConversionSequence ICS;
John McCall6a61b522010-01-13 09:16:55 +00002162 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002163 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002164 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002165 SuppressUserConversions,
2166 /*AllowExplicit=*/false,
2167 ForceRValue,
2168 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002169 return ICS;
2170 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002171 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002172 SuppressUserConversions,
2173 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002174 ForceRValue,
2175 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002176 }
2177}
2178
Sebastian Redl42e92c42009-04-12 17:16:29 +00002179/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2180/// the expression @p From. Returns true (and emits a diagnostic) if there was
2181/// an error, returns false if the initialization succeeded. Elidable should
2182/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2183/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002184bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002185 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002186 if (!getLangOptions().CPlusPlus) {
2187 // In C, argument passing is the same as performing an assignment.
2188 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002189
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002190 AssignConvertType ConvTy =
2191 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002192 if (ConvTy != Compatible &&
2193 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2194 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002195
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002196 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002197 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002198 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002199
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002200 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002201 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002202 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002203 /*SuppressUserConversions=*/false,
2204 /*AllowExplicit=*/false,
2205 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002206
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002207 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002208 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002209 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002210 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002211 return Diag(From->getSourceRange().getBegin(),
2212 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002213 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002214 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002215}
2216
Douglas Gregor436424c2008-11-18 23:14:02 +00002217/// TryObjectArgumentInitialization - Try to initialize the object
2218/// parameter of the given member function (@c Method) from the
2219/// expression @p From.
2220ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002221Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002222 CXXMethodDecl *Method,
2223 CXXRecordDecl *ActingContext) {
2224 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002225 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2226 // const volatile object.
2227 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2228 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2229 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002230
2231 // Set up the conversion sequence as a "bad" conversion, to allow us
2232 // to exit early.
2233 ImplicitConversionSequence ICS;
2234 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002235 ICS.setBad();
Douglas Gregor436424c2008-11-18 23:14:02 +00002236
2237 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002238 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002239 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002240 FromType = PT->getPointeeType();
2241
2242 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002243
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002244 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002245 // where X is the class of which the function is a member
2246 // (C++ [over.match.funcs]p4). However, when finding an implicit
2247 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002248 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002249 // (C++ [over.match.funcs]p5). We perform a simplified version of
2250 // reference binding here, that allows class rvalues to bind to
2251 // non-constant references.
2252
2253 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2254 // with the implicit object parameter (C++ [over.match.funcs]p5).
2255 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002256 if (ImplicitParamType.getCVRQualifiers()
2257 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002258 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall47000992010-01-14 03:28:57 +00002259 ICS.Bad.init(BadConversionSequence::bad_qualifiers,
2260 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002261 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002262 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002263
2264 // Check that we have either the same type or a derived type. It
2265 // affects the conversion rank.
2266 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002267 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002268 ICS.Standard.Second = ICK_Identity;
2269 else if (IsDerivedFrom(FromType, ClassType))
2270 ICS.Standard.Second = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002271 else {
2272 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002273 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002274 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002275
2276 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002277 ICS.setStandard();
2278 ICS.Standard.setFromType(FromType);
2279 ICS.Standard.setToType(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002280 ICS.Standard.ReferenceBinding = true;
2281 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002282 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002283 return ICS;
2284}
2285
2286/// PerformObjectArgumentInitialization - Perform initialization of
2287/// the implicit object parameter for the given Method with the given
2288/// expression.
2289bool
2290Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002291 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002292 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002293 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002294
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002295 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002296 FromRecordType = PT->getPointeeType();
2297 DestType = Method->getThisType(Context);
2298 } else {
2299 FromRecordType = From->getType();
2300 DestType = ImplicitParamRecordType;
2301 }
2302
John McCall6e9f8f62009-12-03 04:06:58 +00002303 // Note that we always use the true parent context when performing
2304 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002305 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002306 = TryObjectArgumentInitialization(From->getType(), Method,
2307 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002308 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002309 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002310 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002311 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002312
Douglas Gregor436424c2008-11-18 23:14:02 +00002313 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002314 CheckDerivedToBaseConversion(FromRecordType,
2315 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002316 From->getSourceRange().getBegin(),
2317 From->getSourceRange()))
2318 return true;
2319
Mike Stump11289f42009-09-09 15:08:12 +00002320 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002321 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002322 return false;
2323}
2324
Douglas Gregor5fb53972009-01-14 15:45:31 +00002325/// TryContextuallyConvertToBool - Attempt to contextually convert the
2326/// expression From to bool (C++0x [conv]p3).
2327ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002328 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002329 // FIXME: Are these flags correct?
2330 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002331 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002332 /*ForceRValue=*/false,
2333 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002334}
2335
2336/// PerformContextuallyConvertToBool - Perform a contextual conversion
2337/// of the expression From to bool (C++0x [conv]p3).
2338bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2339 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002340 if (!ICS.isBad())
2341 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002342
Fariborz Jahanian76197412009-11-18 18:26:29 +00002343 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002344 return Diag(From->getSourceRange().getBegin(),
2345 diag::err_typecheck_bool_condition)
2346 << From->getType() << From->getSourceRange();
2347 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002348}
2349
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002350/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002351/// candidate functions, using the given function call arguments. If
2352/// @p SuppressUserConversions, then don't allow user-defined
2353/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002354/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2355/// hacky way to implement the overloading rules for elidable copy
2356/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002357///
2358/// \para PartialOverloading true if we are performing "partial" overloading
2359/// based on an incomplete set of function arguments. This feature is used by
2360/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002361void
2362Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002363 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002364 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002365 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002366 bool ForceRValue,
2367 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002368 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002369 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002370 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002371 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002372 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002373
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002374 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002375 if (!isa<CXXConstructorDecl>(Method)) {
2376 // If we get here, it's because we're calling a member function
2377 // that is named without a member access expression (e.g.,
2378 // "this->f") that was either written explicitly or created
2379 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002380 // function, e.g., X::f(). We use an empty type for the implied
2381 // object argument (C++ [over.call.func]p3), and the acting context
2382 // is irrelevant.
2383 AddMethodCandidate(Method, Method->getParent(),
2384 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002385 SuppressUserConversions, ForceRValue);
2386 return;
2387 }
2388 // We treat a constructor like a non-member function, since its object
2389 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002390 }
2391
Douglas Gregorff7028a2009-11-13 23:59:09 +00002392 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002393 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002394
Douglas Gregor27381f32009-11-23 12:27:39 +00002395 // Overload resolution is always an unevaluated context.
2396 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2397
Douglas Gregorffe14e32009-11-14 01:20:54 +00002398 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2399 // C++ [class.copy]p3:
2400 // A member function template is never instantiated to perform the copy
2401 // of a class object to an object of its class type.
2402 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2403 if (NumArgs == 1 &&
2404 Constructor->isCopyConstructorLikeSpecialization() &&
2405 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2406 return;
2407 }
2408
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002409 // Add this candidate
2410 CandidateSet.push_back(OverloadCandidate());
2411 OverloadCandidate& Candidate = CandidateSet.back();
2412 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002413 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002414 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002415 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002416
2417 unsigned NumArgsInProto = Proto->getNumArgs();
2418
2419 // (C++ 13.3.2p2): A candidate function having fewer than m
2420 // parameters is viable only if it has an ellipsis in its parameter
2421 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002422 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2423 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002424 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002425 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002426 return;
2427 }
2428
2429 // (C++ 13.3.2p2): A candidate function having more than m parameters
2430 // is viable only if the (m+1)st parameter has a default argument
2431 // (8.3.6). For the purposes of overload resolution, the
2432 // parameter list is truncated on the right, so that there are
2433 // exactly m parameters.
2434 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002435 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002436 // Not enough arguments.
2437 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002438 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002439 return;
2440 }
2441
2442 // Determine the implicit conversion sequences for each of the
2443 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002444 Candidate.Conversions.resize(NumArgs);
2445 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2446 if (ArgIdx < NumArgsInProto) {
2447 // (C++ 13.3.2p3): for F to be a viable function, there shall
2448 // exist for each argument an implicit conversion sequence
2449 // (13.3.3.1) that converts that argument to the corresponding
2450 // parameter of F.
2451 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002452 Candidate.Conversions[ArgIdx]
2453 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002454 SuppressUserConversions, ForceRValue,
2455 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002456 if (Candidate.Conversions[ArgIdx].isBad()) {
2457 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002458 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002459 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002460 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002461 } else {
2462 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2463 // argument for which there is no corresponding parameter is
2464 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002465 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002466 }
2467 }
2468}
2469
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002470/// \brief Add all of the function declarations in the given function set to
2471/// the overload canddiate set.
2472void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2473 Expr **Args, unsigned NumArgs,
2474 OverloadCandidateSet& CandidateSet,
2475 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002476 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002477 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002478 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002479 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002480 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2481 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2482 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002483 cast<CXXMethodDecl>(FD)->getParent(),
2484 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002485 CandidateSet, SuppressUserConversions);
2486 else
2487 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2488 SuppressUserConversions);
2489 } else {
2490 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2491 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2492 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2493 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002494 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002495 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002496 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002497 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002498 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002499 else
2500 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002501 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002502 Args, NumArgs, CandidateSet,
2503 SuppressUserConversions);
2504 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002505 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002506}
2507
John McCallf0f1cf02009-11-17 07:50:12 +00002508/// AddMethodCandidate - Adds a named decl (which is some kind of
2509/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002510void Sema::AddMethodCandidate(NamedDecl *Decl,
2511 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002512 Expr **Args, unsigned NumArgs,
2513 OverloadCandidateSet& CandidateSet,
2514 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002515 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002516
2517 if (isa<UsingShadowDecl>(Decl))
2518 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2519
2520 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2521 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2522 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002523 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2524 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002525 CandidateSet,
2526 SuppressUserConversions,
2527 ForceRValue);
2528 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002529 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2530 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002531 CandidateSet, SuppressUserConversions, ForceRValue);
2532 }
2533}
2534
Douglas Gregor436424c2008-11-18 23:14:02 +00002535/// AddMethodCandidate - Adds the given C++ member function to the set
2536/// of candidate functions, using the given function call arguments
2537/// and the object argument (@c Object). For example, in a call
2538/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2539/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2540/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002541/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2542/// a slightly hacky way to implement the overloading rules for elidable copy
2543/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002544void
John McCall6e9f8f62009-12-03 04:06:58 +00002545Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2546 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002547 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002548 bool SuppressUserConversions, bool ForceRValue) {
2549 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002550 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002551 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002552 assert(!isa<CXXConstructorDecl>(Method) &&
2553 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002554
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002555 if (!CandidateSet.isNewCandidate(Method))
2556 return;
2557
Douglas Gregor27381f32009-11-23 12:27:39 +00002558 // Overload resolution is always an unevaluated context.
2559 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2560
Douglas Gregor436424c2008-11-18 23:14:02 +00002561 // Add this candidate
2562 CandidateSet.push_back(OverloadCandidate());
2563 OverloadCandidate& Candidate = CandidateSet.back();
2564 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002565 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002566 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002567
2568 unsigned NumArgsInProto = Proto->getNumArgs();
2569
2570 // (C++ 13.3.2p2): A candidate function having fewer than m
2571 // parameters is viable only if it has an ellipsis in its parameter
2572 // list (8.3.5).
2573 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2574 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002575 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002576 return;
2577 }
2578
2579 // (C++ 13.3.2p2): A candidate function having more than m parameters
2580 // is viable only if the (m+1)st parameter has a default argument
2581 // (8.3.6). For the purposes of overload resolution, the
2582 // parameter list is truncated on the right, so that there are
2583 // exactly m parameters.
2584 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2585 if (NumArgs < MinRequiredArgs) {
2586 // Not enough arguments.
2587 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002588 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002589 return;
2590 }
2591
2592 Candidate.Viable = true;
2593 Candidate.Conversions.resize(NumArgs + 1);
2594
John McCall6e9f8f62009-12-03 04:06:58 +00002595 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002596 // The implicit object argument is ignored.
2597 Candidate.IgnoreObjectArgument = true;
2598 else {
2599 // Determine the implicit conversion sequence for the object
2600 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002601 Candidate.Conversions[0]
2602 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002603 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002604 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002605 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002606 return;
2607 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002608 }
2609
2610 // Determine the implicit conversion sequences for each of the
2611 // arguments.
2612 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2613 if (ArgIdx < NumArgsInProto) {
2614 // (C++ 13.3.2p3): for F to be a viable function, there shall
2615 // exist for each argument an implicit conversion sequence
2616 // (13.3.3.1) that converts that argument to the corresponding
2617 // parameter of F.
2618 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002619 Candidate.Conversions[ArgIdx + 1]
2620 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002621 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002622 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002623 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002624 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002625 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002626 break;
2627 }
2628 } else {
2629 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2630 // argument for which there is no corresponding parameter is
2631 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002632 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002633 }
2634 }
2635}
2636
Douglas Gregor97628d62009-08-21 00:16:32 +00002637/// \brief Add a C++ member function template as a candidate to the candidate
2638/// set, using template argument deduction to produce an appropriate member
2639/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002640void
Douglas Gregor97628d62009-08-21 00:16:32 +00002641Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002642 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002643 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002644 QualType ObjectType,
2645 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002646 OverloadCandidateSet& CandidateSet,
2647 bool SuppressUserConversions,
2648 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002649 if (!CandidateSet.isNewCandidate(MethodTmpl))
2650 return;
2651
Douglas Gregor97628d62009-08-21 00:16:32 +00002652 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002653 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002654 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002655 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002656 // candidate functions in the usual way.113) A given name can refer to one
2657 // or more function templates and also to a set of overloaded non-template
2658 // functions. In such a case, the candidate functions generated from each
2659 // function template are combined with the set of non-template candidate
2660 // functions.
2661 TemplateDeductionInfo Info(Context);
2662 FunctionDecl *Specialization = 0;
2663 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002664 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002665 Args, NumArgs, Specialization, Info)) {
2666 // FIXME: Record what happened with template argument deduction, so
2667 // that we can give the user a beautiful diagnostic.
2668 (void)Result;
2669 return;
2670 }
Mike Stump11289f42009-09-09 15:08:12 +00002671
Douglas Gregor97628d62009-08-21 00:16:32 +00002672 // Add the function template specialization produced by template argument
2673 // deduction as a candidate.
2674 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002675 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002676 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002677 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2678 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002679 CandidateSet, SuppressUserConversions, ForceRValue);
2680}
2681
Douglas Gregor05155d82009-08-21 23:19:43 +00002682/// \brief Add a C++ function template specialization as a candidate
2683/// in the candidate set, using template argument deduction to produce
2684/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002685void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002686Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002687 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002688 Expr **Args, unsigned NumArgs,
2689 OverloadCandidateSet& CandidateSet,
2690 bool SuppressUserConversions,
2691 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002692 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2693 return;
2694
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002695 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002696 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002697 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002698 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002699 // candidate functions in the usual way.113) A given name can refer to one
2700 // or more function templates and also to a set of overloaded non-template
2701 // functions. In such a case, the candidate functions generated from each
2702 // function template are combined with the set of non-template candidate
2703 // functions.
2704 TemplateDeductionInfo Info(Context);
2705 FunctionDecl *Specialization = 0;
2706 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002707 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002708 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002709 // FIXME: Record what happened with template argument deduction, so
2710 // that we can give the user a beautiful diagnostic.
John McCalld681c392009-12-16 08:11:27 +00002711 (void) Result;
2712
2713 CandidateSet.push_back(OverloadCandidate());
2714 OverloadCandidate &Candidate = CandidateSet.back();
2715 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2716 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002717 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002718 Candidate.IsSurrogate = false;
2719 Candidate.IgnoreObjectArgument = false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002720 return;
2721 }
Mike Stump11289f42009-09-09 15:08:12 +00002722
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002723 // Add the function template specialization produced by template argument
2724 // deduction as a candidate.
2725 assert(Specialization && "Missing function template specialization?");
2726 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2727 SuppressUserConversions, ForceRValue);
2728}
Mike Stump11289f42009-09-09 15:08:12 +00002729
Douglas Gregora1f013e2008-11-07 22:36:19 +00002730/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002731/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002732/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002733/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002734/// (which may or may not be the same type as the type that the
2735/// conversion function produces).
2736void
2737Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002738 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002739 Expr *From, QualType ToType,
2740 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002741 assert(!Conversion->getDescribedFunctionTemplate() &&
2742 "Conversion function templates use AddTemplateConversionCandidate");
2743
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002744 if (!CandidateSet.isNewCandidate(Conversion))
2745 return;
2746
Douglas Gregor27381f32009-11-23 12:27:39 +00002747 // Overload resolution is always an unevaluated context.
2748 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2749
Douglas Gregora1f013e2008-11-07 22:36:19 +00002750 // Add this candidate
2751 CandidateSet.push_back(OverloadCandidate());
2752 OverloadCandidate& Candidate = CandidateSet.back();
2753 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002754 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002755 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002756 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002757 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
2758 Candidate.FinalConversion.setToType(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002759
Douglas Gregor436424c2008-11-18 23:14:02 +00002760 // Determine the implicit conversion sequence for the implicit
2761 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002762 Candidate.Viable = true;
2763 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002764 Candidate.Conversions[0]
2765 = TryObjectArgumentInitialization(From->getType(), Conversion,
2766 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002767 // Conversion functions to a different type in the base class is visible in
2768 // the derived class. So, a derived to base conversion should not participate
2769 // in overload resolution.
2770 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2771 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002772 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002773 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002774 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002775 return;
2776 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002777
2778 // We won't go through a user-define type conversion function to convert a
2779 // derived to base as such conversions are given Conversion Rank. They only
2780 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2781 QualType FromCanon
2782 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2783 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2784 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2785 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002786 Candidate.FailureKind = ovl_fail_bad_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002787 return;
2788 }
2789
Douglas Gregora1f013e2008-11-07 22:36:19 +00002790
2791 // To determine what the conversion from the result of calling the
2792 // conversion function to the type we're eventually trying to
2793 // convert to (ToType), we need to synthesize a call to the
2794 // conversion function and attempt copy initialization from it. This
2795 // makes sure that we get the right semantics with respect to
2796 // lvalues/rvalues and the type. Fortunately, we can allocate this
2797 // call on the stack and we don't need its arguments to be
2798 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002799 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002800 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002801 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002802 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002803 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002804
2805 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002806 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2807 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002808 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002809 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002810 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002811 ImplicitConversionSequence ICS =
2812 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002813 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002814 /*ForceRValue=*/false,
2815 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002816
John McCall0d1da222010-01-12 00:44:57 +00002817 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002818 case ImplicitConversionSequence::StandardConversion:
2819 Candidate.FinalConversion = ICS.Standard;
2820 break;
2821
2822 case ImplicitConversionSequence::BadConversion:
2823 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002824 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002825 break;
2826
2827 default:
Mike Stump11289f42009-09-09 15:08:12 +00002828 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002829 "Can only end up with a standard conversion sequence or failure");
2830 }
2831}
2832
Douglas Gregor05155d82009-08-21 23:19:43 +00002833/// \brief Adds a conversion function template specialization
2834/// candidate to the overload set, using template argument deduction
2835/// to deduce the template arguments of the conversion function
2836/// template from the type that we are converting to (C++
2837/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002838void
Douglas Gregor05155d82009-08-21 23:19:43 +00002839Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002840 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002841 Expr *From, QualType ToType,
2842 OverloadCandidateSet &CandidateSet) {
2843 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2844 "Only conversion function templates permitted here");
2845
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002846 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2847 return;
2848
Douglas Gregor05155d82009-08-21 23:19:43 +00002849 TemplateDeductionInfo Info(Context);
2850 CXXConversionDecl *Specialization = 0;
2851 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002852 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002853 Specialization, Info)) {
2854 // FIXME: Record what happened with template argument deduction, so
2855 // that we can give the user a beautiful diagnostic.
2856 (void)Result;
2857 return;
2858 }
Mike Stump11289f42009-09-09 15:08:12 +00002859
Douglas Gregor05155d82009-08-21 23:19:43 +00002860 // Add the conversion function template specialization produced by
2861 // template argument deduction as a candidate.
2862 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002863 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002864}
2865
Douglas Gregorab7897a2008-11-19 22:57:39 +00002866/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2867/// converts the given @c Object to a function pointer via the
2868/// conversion function @c Conversion, and then attempts to call it
2869/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2870/// the type of function that we'll eventually be calling.
2871void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002872 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002873 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002874 QualType ObjectType,
2875 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002876 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002877 if (!CandidateSet.isNewCandidate(Conversion))
2878 return;
2879
Douglas Gregor27381f32009-11-23 12:27:39 +00002880 // Overload resolution is always an unevaluated context.
2881 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2882
Douglas Gregorab7897a2008-11-19 22:57:39 +00002883 CandidateSet.push_back(OverloadCandidate());
2884 OverloadCandidate& Candidate = CandidateSet.back();
2885 Candidate.Function = 0;
2886 Candidate.Surrogate = Conversion;
2887 Candidate.Viable = true;
2888 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002889 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002890 Candidate.Conversions.resize(NumArgs + 1);
2891
2892 // Determine the implicit conversion sequence for the implicit
2893 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002894 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002895 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002896 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002897 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002898 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002899 return;
2900 }
2901
2902 // The first conversion is actually a user-defined conversion whose
2903 // first conversion is ObjectInit's standard conversion (which is
2904 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002905 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002906 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002907 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002908 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002909 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002910 = Candidate.Conversions[0].UserDefined.Before;
2911 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2912
Mike Stump11289f42009-09-09 15:08:12 +00002913 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002914 unsigned NumArgsInProto = Proto->getNumArgs();
2915
2916 // (C++ 13.3.2p2): A candidate function having fewer than m
2917 // parameters is viable only if it has an ellipsis in its parameter
2918 // list (8.3.5).
2919 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2920 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002921 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002922 return;
2923 }
2924
2925 // Function types don't have any default arguments, so just check if
2926 // we have enough arguments.
2927 if (NumArgs < NumArgsInProto) {
2928 // Not enough arguments.
2929 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002930 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002931 return;
2932 }
2933
2934 // Determine the implicit conversion sequences for each of the
2935 // arguments.
2936 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2937 if (ArgIdx < NumArgsInProto) {
2938 // (C++ 13.3.2p3): for F to be a viable function, there shall
2939 // exist for each argument an implicit conversion sequence
2940 // (13.3.3.1) that converts that argument to the corresponding
2941 // parameter of F.
2942 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002943 Candidate.Conversions[ArgIdx + 1]
2944 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002945 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002946 /*ForceRValue=*/false,
2947 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002948 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002949 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002950 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002951 break;
2952 }
2953 } else {
2954 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2955 // argument for which there is no corresponding parameter is
2956 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002957 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002958 }
2959 }
2960}
2961
Mike Stump87c57ac2009-05-16 07:39:55 +00002962// FIXME: This will eventually be removed, once we've migrated all of the
2963// operator overloading logic over to the scheme used by binary operators, which
2964// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002965void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002966 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002967 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002968 OverloadCandidateSet& CandidateSet,
2969 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002970 FunctionSet Functions;
2971
2972 QualType T1 = Args[0]->getType();
2973 QualType T2;
2974 if (NumArgs > 1)
2975 T2 = Args[1]->getType();
2976
2977 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002978 if (S)
2979 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002980 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002981 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2982 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002983 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002984}
2985
2986/// \brief Add overload candidates for overloaded operators that are
2987/// member functions.
2988///
2989/// Add the overloaded operator candidates that are member functions
2990/// for the operator Op that was used in an operator expression such
2991/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2992/// CandidateSet will store the added overload candidates. (C++
2993/// [over.match.oper]).
2994void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2995 SourceLocation OpLoc,
2996 Expr **Args, unsigned NumArgs,
2997 OverloadCandidateSet& CandidateSet,
2998 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002999 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3000
3001 // C++ [over.match.oper]p3:
3002 // For a unary operator @ with an operand of a type whose
3003 // cv-unqualified version is T1, and for a binary operator @ with
3004 // a left operand of a type whose cv-unqualified version is T1 and
3005 // a right operand of a type whose cv-unqualified version is T2,
3006 // three sets of candidate functions, designated member
3007 // candidates, non-member candidates and built-in candidates, are
3008 // constructed as follows:
3009 QualType T1 = Args[0]->getType();
3010 QualType T2;
3011 if (NumArgs > 1)
3012 T2 = Args[1]->getType();
3013
3014 // -- If T1 is a class type, the set of member candidates is the
3015 // result of the qualified lookup of T1::operator@
3016 // (13.3.1.1.1); otherwise, the set of member candidates is
3017 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003018 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003019 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003020 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003021 return;
Mike Stump11289f42009-09-09 15:08:12 +00003022
John McCall27b18f82009-11-17 02:14:36 +00003023 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3024 LookupQualifiedName(Operators, T1Rec->getDecl());
3025 Operators.suppressDiagnostics();
3026
Mike Stump11289f42009-09-09 15:08:12 +00003027 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003028 OperEnd = Operators.end();
3029 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003030 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00003031 AddMethodCandidate(*Oper, Args[0]->getType(),
3032 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003033 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003034 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003035}
3036
Douglas Gregora11693b2008-11-12 17:17:38 +00003037/// AddBuiltinCandidate - Add a candidate for a built-in
3038/// operator. ResultTy and ParamTys are the result and parameter types
3039/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003040/// arguments being passed to the candidate. IsAssignmentOperator
3041/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003042/// operator. NumContextualBoolArguments is the number of arguments
3043/// (at the beginning of the argument list) that will be contextually
3044/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003045void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003046 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003047 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003048 bool IsAssignmentOperator,
3049 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003050 // Overload resolution is always an unevaluated context.
3051 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3052
Douglas Gregora11693b2008-11-12 17:17:38 +00003053 // Add this candidate
3054 CandidateSet.push_back(OverloadCandidate());
3055 OverloadCandidate& Candidate = CandidateSet.back();
3056 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003057 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003058 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003059 Candidate.BuiltinTypes.ResultTy = ResultTy;
3060 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3061 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3062
3063 // Determine the implicit conversion sequences for each of the
3064 // arguments.
3065 Candidate.Viable = true;
3066 Candidate.Conversions.resize(NumArgs);
3067 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003068 // C++ [over.match.oper]p4:
3069 // For the built-in assignment operators, conversions of the
3070 // left operand are restricted as follows:
3071 // -- no temporaries are introduced to hold the left operand, and
3072 // -- no user-defined conversions are applied to the left
3073 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003074 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003075 //
3076 // We block these conversions by turning off user-defined
3077 // conversions, since that is the only way that initialization of
3078 // a reference to a non-class type can occur from something that
3079 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003080 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003081 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003082 "Contextual conversion to bool requires bool type");
3083 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3084 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003085 Candidate.Conversions[ArgIdx]
3086 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003087 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003088 /*ForceRValue=*/false,
3089 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003090 }
John McCall0d1da222010-01-12 00:44:57 +00003091 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003092 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003093 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003094 break;
3095 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003096 }
3097}
3098
3099/// BuiltinCandidateTypeSet - A set of types that will be used for the
3100/// candidate operator functions for built-in operators (C++
3101/// [over.built]). The types are separated into pointer types and
3102/// enumeration types.
3103class BuiltinCandidateTypeSet {
3104 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003105 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003106
3107 /// PointerTypes - The set of pointer types that will be used in the
3108 /// built-in candidates.
3109 TypeSet PointerTypes;
3110
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003111 /// MemberPointerTypes - The set of member pointer types that will be
3112 /// used in the built-in candidates.
3113 TypeSet MemberPointerTypes;
3114
Douglas Gregora11693b2008-11-12 17:17:38 +00003115 /// EnumerationTypes - The set of enumeration types that will be
3116 /// used in the built-in candidates.
3117 TypeSet EnumerationTypes;
3118
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003119 /// Sema - The semantic analysis instance where we are building the
3120 /// candidate type set.
3121 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003122
Douglas Gregora11693b2008-11-12 17:17:38 +00003123 /// Context - The AST context in which we will build the type sets.
3124 ASTContext &Context;
3125
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003126 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3127 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003128 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003129
3130public:
3131 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003132 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003133
Mike Stump11289f42009-09-09 15:08:12 +00003134 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003135 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003136
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003137 void AddTypesConvertedFrom(QualType Ty,
3138 SourceLocation Loc,
3139 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003140 bool AllowExplicitConversions,
3141 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003142
3143 /// pointer_begin - First pointer type found;
3144 iterator pointer_begin() { return PointerTypes.begin(); }
3145
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003146 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003147 iterator pointer_end() { return PointerTypes.end(); }
3148
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003149 /// member_pointer_begin - First member pointer type found;
3150 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3151
3152 /// member_pointer_end - Past the last member pointer type found;
3153 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3154
Douglas Gregora11693b2008-11-12 17:17:38 +00003155 /// enumeration_begin - First enumeration type found;
3156 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3157
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003158 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003159 iterator enumeration_end() { return EnumerationTypes.end(); }
3160};
3161
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003162/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003163/// the set of pointer types along with any more-qualified variants of
3164/// that type. For example, if @p Ty is "int const *", this routine
3165/// will add "int const *", "int const volatile *", "int const
3166/// restrict *", and "int const volatile restrict *" to the set of
3167/// pointer types. Returns true if the add of @p Ty itself succeeded,
3168/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003169///
3170/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003171bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003172BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3173 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003174
Douglas Gregora11693b2008-11-12 17:17:38 +00003175 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003176 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003177 return false;
3178
John McCall8ccfcb52009-09-24 19:53:00 +00003179 const PointerType *PointerTy = Ty->getAs<PointerType>();
3180 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003181
John McCall8ccfcb52009-09-24 19:53:00 +00003182 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003183 // Don't add qualified variants of arrays. For one, they're not allowed
3184 // (the qualifier would sink to the element type), and for another, the
3185 // only overload situation where it matters is subscript or pointer +- int,
3186 // and those shouldn't have qualifier variants anyway.
3187 if (PointeeTy->isArrayType())
3188 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003189 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003190 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003191 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003192 bool hasVolatile = VisibleQuals.hasVolatile();
3193 bool hasRestrict = VisibleQuals.hasRestrict();
3194
John McCall8ccfcb52009-09-24 19:53:00 +00003195 // Iterate through all strict supersets of BaseCVR.
3196 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3197 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003198 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3199 // in the types.
3200 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3201 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003202 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3203 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003204 }
3205
3206 return true;
3207}
3208
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003209/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3210/// to the set of pointer types along with any more-qualified variants of
3211/// that type. For example, if @p Ty is "int const *", this routine
3212/// will add "int const *", "int const volatile *", "int const
3213/// restrict *", and "int const volatile restrict *" to the set of
3214/// pointer types. Returns true if the add of @p Ty itself succeeded,
3215/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003216///
3217/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003218bool
3219BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3220 QualType Ty) {
3221 // Insert this type.
3222 if (!MemberPointerTypes.insert(Ty))
3223 return false;
3224
John McCall8ccfcb52009-09-24 19:53:00 +00003225 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3226 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003227
John McCall8ccfcb52009-09-24 19:53:00 +00003228 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003229 // Don't add qualified variants of arrays. For one, they're not allowed
3230 // (the qualifier would sink to the element type), and for another, the
3231 // only overload situation where it matters is subscript or pointer +- int,
3232 // and those shouldn't have qualifier variants anyway.
3233 if (PointeeTy->isArrayType())
3234 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003235 const Type *ClassTy = PointerTy->getClass();
3236
3237 // Iterate through all strict supersets of the pointee type's CVR
3238 // qualifiers.
3239 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3240 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3241 if ((CVR | BaseCVR) != CVR) continue;
3242
3243 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3244 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003245 }
3246
3247 return true;
3248}
3249
Douglas Gregora11693b2008-11-12 17:17:38 +00003250/// AddTypesConvertedFrom - Add each of the types to which the type @p
3251/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003252/// primarily interested in pointer types and enumeration types. We also
3253/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003254/// AllowUserConversions is true if we should look at the conversion
3255/// functions of a class type, and AllowExplicitConversions if we
3256/// should also include the explicit conversion functions of a class
3257/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003258void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003259BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003260 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003261 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003262 bool AllowExplicitConversions,
3263 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003264 // Only deal with canonical types.
3265 Ty = Context.getCanonicalType(Ty);
3266
3267 // Look through reference types; they aren't part of the type of an
3268 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003269 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003270 Ty = RefTy->getPointeeType();
3271
3272 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003273 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003274
Sebastian Redl65ae2002009-11-05 16:36:20 +00003275 // If we're dealing with an array type, decay to the pointer.
3276 if (Ty->isArrayType())
3277 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3278
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003279 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003280 QualType PointeeTy = PointerTy->getPointeeType();
3281
3282 // Insert our type, and its more-qualified variants, into the set
3283 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003284 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003285 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003286 } else if (Ty->isMemberPointerType()) {
3287 // Member pointers are far easier, since the pointee can't be converted.
3288 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3289 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003290 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003291 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003292 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003293 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003294 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003295 // No conversion functions in incomplete types.
3296 return;
3297 }
Mike Stump11289f42009-09-09 15:08:12 +00003298
Douglas Gregora11693b2008-11-12 17:17:38 +00003299 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003300 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003301 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003302 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003303 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003304
Mike Stump11289f42009-09-09 15:08:12 +00003305 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003306 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003307 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003308 continue;
3309
John McCalld14a8642009-11-21 08:51:07 +00003310 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003311 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003312 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003313 VisibleQuals);
3314 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003315 }
3316 }
3317 }
3318}
3319
Douglas Gregor84605ae2009-08-24 13:43:27 +00003320/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3321/// the volatile- and non-volatile-qualified assignment operators for the
3322/// given type to the candidate set.
3323static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3324 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003325 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003326 unsigned NumArgs,
3327 OverloadCandidateSet &CandidateSet) {
3328 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003329
Douglas Gregor84605ae2009-08-24 13:43:27 +00003330 // T& operator=(T&, T)
3331 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3332 ParamTypes[1] = T;
3333 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3334 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003335
Douglas Gregor84605ae2009-08-24 13:43:27 +00003336 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3337 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003338 ParamTypes[0]
3339 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003340 ParamTypes[1] = T;
3341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003342 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003343 }
3344}
Mike Stump11289f42009-09-09 15:08:12 +00003345
Sebastian Redl1054fae2009-10-25 17:03:50 +00003346/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3347/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003348static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3349 Qualifiers VRQuals;
3350 const RecordType *TyRec;
3351 if (const MemberPointerType *RHSMPType =
3352 ArgExpr->getType()->getAs<MemberPointerType>())
3353 TyRec = cast<RecordType>(RHSMPType->getClass());
3354 else
3355 TyRec = ArgExpr->getType()->getAs<RecordType>();
3356 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003357 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003358 VRQuals.addVolatile();
3359 VRQuals.addRestrict();
3360 return VRQuals;
3361 }
3362
3363 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003364 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003365 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003366
John McCallad371252010-01-20 00:46:10 +00003367 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003368 E = Conversions->end(); I != E; ++I) {
3369 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003370 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3371 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3372 CanTy = ResTypeRef->getPointeeType();
3373 // Need to go down the pointer/mempointer chain and add qualifiers
3374 // as see them.
3375 bool done = false;
3376 while (!done) {
3377 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3378 CanTy = ResTypePtr->getPointeeType();
3379 else if (const MemberPointerType *ResTypeMPtr =
3380 CanTy->getAs<MemberPointerType>())
3381 CanTy = ResTypeMPtr->getPointeeType();
3382 else
3383 done = true;
3384 if (CanTy.isVolatileQualified())
3385 VRQuals.addVolatile();
3386 if (CanTy.isRestrictQualified())
3387 VRQuals.addRestrict();
3388 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3389 return VRQuals;
3390 }
3391 }
3392 }
3393 return VRQuals;
3394}
3395
Douglas Gregord08452f2008-11-19 15:42:04 +00003396/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3397/// operator overloads to the candidate set (C++ [over.built]), based
3398/// on the operator @p Op and the arguments given. For example, if the
3399/// operator is a binary '+', this routine might add "int
3400/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003401void
Mike Stump11289f42009-09-09 15:08:12 +00003402Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003403 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003404 Expr **Args, unsigned NumArgs,
3405 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003406 // The set of "promoted arithmetic types", which are the arithmetic
3407 // types are that preserved by promotion (C++ [over.built]p2). Note
3408 // that the first few of these types are the promoted integral
3409 // types; these types need to be first.
3410 // FIXME: What about complex?
3411 const unsigned FirstIntegralType = 0;
3412 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003413 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003414 LastPromotedIntegralType = 13;
3415 const unsigned FirstPromotedArithmeticType = 7,
3416 LastPromotedArithmeticType = 16;
3417 const unsigned NumArithmeticTypes = 16;
3418 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003419 Context.BoolTy, Context.CharTy, Context.WCharTy,
3420// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003421 Context.SignedCharTy, Context.ShortTy,
3422 Context.UnsignedCharTy, Context.UnsignedShortTy,
3423 Context.IntTy, Context.LongTy, Context.LongLongTy,
3424 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3425 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3426 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003427 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3428 "Invalid first promoted integral type");
3429 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3430 == Context.UnsignedLongLongTy &&
3431 "Invalid last promoted integral type");
3432 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3433 "Invalid first promoted arithmetic type");
3434 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3435 == Context.LongDoubleTy &&
3436 "Invalid last promoted arithmetic type");
3437
Douglas Gregora11693b2008-11-12 17:17:38 +00003438 // Find all of the types that the arguments can convert to, but only
3439 // if the operator we're looking at has built-in operator candidates
3440 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003441 Qualifiers VisibleTypeConversionsQuals;
3442 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003443 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3444 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3445
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003446 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003447 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3448 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003449 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003450 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003451 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003452 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003453 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003454 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003455 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003456 true,
3457 (Op == OO_Exclaim ||
3458 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003459 Op == OO_PipePipe),
3460 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003461 }
3462
3463 bool isComparison = false;
3464 switch (Op) {
3465 case OO_None:
3466 case NUM_OVERLOADED_OPERATORS:
3467 assert(false && "Expected an overloaded operator");
3468 break;
3469
Douglas Gregord08452f2008-11-19 15:42:04 +00003470 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003471 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003472 goto UnaryStar;
3473 else
3474 goto BinaryStar;
3475 break;
3476
3477 case OO_Plus: // '+' is either unary or binary
3478 if (NumArgs == 1)
3479 goto UnaryPlus;
3480 else
3481 goto BinaryPlus;
3482 break;
3483
3484 case OO_Minus: // '-' is either unary or binary
3485 if (NumArgs == 1)
3486 goto UnaryMinus;
3487 else
3488 goto BinaryMinus;
3489 break;
3490
3491 case OO_Amp: // '&' is either unary or binary
3492 if (NumArgs == 1)
3493 goto UnaryAmp;
3494 else
3495 goto BinaryAmp;
3496
3497 case OO_PlusPlus:
3498 case OO_MinusMinus:
3499 // C++ [over.built]p3:
3500 //
3501 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3502 // is either volatile or empty, there exist candidate operator
3503 // functions of the form
3504 //
3505 // VQ T& operator++(VQ T&);
3506 // T operator++(VQ T&, int);
3507 //
3508 // C++ [over.built]p4:
3509 //
3510 // For every pair (T, VQ), where T is an arithmetic type other
3511 // than bool, and VQ is either volatile or empty, there exist
3512 // candidate operator functions of the form
3513 //
3514 // VQ T& operator--(VQ T&);
3515 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003516 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003517 Arith < NumArithmeticTypes; ++Arith) {
3518 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003519 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003520 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003521
3522 // Non-volatile version.
3523 if (NumArgs == 1)
3524 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3525 else
3526 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003527 // heuristic to reduce number of builtin candidates in the set.
3528 // Add volatile version only if there are conversions to a volatile type.
3529 if (VisibleTypeConversionsQuals.hasVolatile()) {
3530 // Volatile version
3531 ParamTypes[0]
3532 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3533 if (NumArgs == 1)
3534 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3535 else
3536 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3537 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003538 }
3539
3540 // C++ [over.built]p5:
3541 //
3542 // For every pair (T, VQ), where T is a cv-qualified or
3543 // cv-unqualified object type, and VQ is either volatile or
3544 // empty, there exist candidate operator functions of the form
3545 //
3546 // T*VQ& operator++(T*VQ&);
3547 // T*VQ& operator--(T*VQ&);
3548 // T* operator++(T*VQ&, int);
3549 // T* operator--(T*VQ&, int);
3550 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3551 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3552 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003553 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003554 continue;
3555
Mike Stump11289f42009-09-09 15:08:12 +00003556 QualType ParamTypes[2] = {
3557 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003558 };
Mike Stump11289f42009-09-09 15:08:12 +00003559
Douglas Gregord08452f2008-11-19 15:42:04 +00003560 // Without volatile
3561 if (NumArgs == 1)
3562 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3563 else
3564 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3565
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003566 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3567 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003568 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003569 ParamTypes[0]
3570 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003571 if (NumArgs == 1)
3572 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3573 else
3574 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3575 }
3576 }
3577 break;
3578
3579 UnaryStar:
3580 // C++ [over.built]p6:
3581 // For every cv-qualified or cv-unqualified object type T, there
3582 // exist candidate operator functions of the form
3583 //
3584 // T& operator*(T*);
3585 //
3586 // C++ [over.built]p7:
3587 // For every function type T, there exist candidate operator
3588 // functions of the form
3589 // T& operator*(T*);
3590 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3591 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3592 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003593 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003594 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003595 &ParamTy, Args, 1, CandidateSet);
3596 }
3597 break;
3598
3599 UnaryPlus:
3600 // C++ [over.built]p8:
3601 // For every type T, there exist candidate operator functions of
3602 // the form
3603 //
3604 // T* operator+(T*);
3605 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3606 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3607 QualType ParamTy = *Ptr;
3608 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3609 }
Mike Stump11289f42009-09-09 15:08:12 +00003610
Douglas Gregord08452f2008-11-19 15:42:04 +00003611 // Fall through
3612
3613 UnaryMinus:
3614 // C++ [over.built]p9:
3615 // For every promoted arithmetic type T, there exist candidate
3616 // operator functions of the form
3617 //
3618 // T operator+(T);
3619 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003620 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003621 Arith < LastPromotedArithmeticType; ++Arith) {
3622 QualType ArithTy = ArithmeticTypes[Arith];
3623 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3624 }
3625 break;
3626
3627 case OO_Tilde:
3628 // C++ [over.built]p10:
3629 // For every promoted integral type T, there exist candidate
3630 // operator functions of the form
3631 //
3632 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003633 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003634 Int < LastPromotedIntegralType; ++Int) {
3635 QualType IntTy = ArithmeticTypes[Int];
3636 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3637 }
3638 break;
3639
Douglas Gregora11693b2008-11-12 17:17:38 +00003640 case OO_New:
3641 case OO_Delete:
3642 case OO_Array_New:
3643 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003644 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003645 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003646 break;
3647
3648 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003649 UnaryAmp:
3650 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003651 // C++ [over.match.oper]p3:
3652 // -- For the operator ',', the unary operator '&', or the
3653 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003654 break;
3655
Douglas Gregor84605ae2009-08-24 13:43:27 +00003656 case OO_EqualEqual:
3657 case OO_ExclaimEqual:
3658 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003659 // For every pointer to member type T, there exist candidate operator
3660 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003661 //
3662 // bool operator==(T,T);
3663 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003664 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003665 MemPtr = CandidateTypes.member_pointer_begin(),
3666 MemPtrEnd = CandidateTypes.member_pointer_end();
3667 MemPtr != MemPtrEnd;
3668 ++MemPtr) {
3669 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3670 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3671 }
Mike Stump11289f42009-09-09 15:08:12 +00003672
Douglas Gregor84605ae2009-08-24 13:43:27 +00003673 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003674
Douglas Gregora11693b2008-11-12 17:17:38 +00003675 case OO_Less:
3676 case OO_Greater:
3677 case OO_LessEqual:
3678 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003679 // C++ [over.built]p15:
3680 //
3681 // For every pointer or enumeration type T, there exist
3682 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003683 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003684 // bool operator<(T, T);
3685 // bool operator>(T, T);
3686 // bool operator<=(T, T);
3687 // bool operator>=(T, T);
3688 // bool operator==(T, T);
3689 // bool operator!=(T, T);
3690 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3691 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3692 QualType ParamTypes[2] = { *Ptr, *Ptr };
3693 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3694 }
Mike Stump11289f42009-09-09 15:08:12 +00003695 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003696 = CandidateTypes.enumeration_begin();
3697 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3698 QualType ParamTypes[2] = { *Enum, *Enum };
3699 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3700 }
3701
3702 // Fall through.
3703 isComparison = true;
3704
Douglas Gregord08452f2008-11-19 15:42:04 +00003705 BinaryPlus:
3706 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003707 if (!isComparison) {
3708 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3709
3710 // C++ [over.built]p13:
3711 //
3712 // For every cv-qualified or cv-unqualified object type T
3713 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003714 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003715 // T* operator+(T*, ptrdiff_t);
3716 // T& operator[](T*, ptrdiff_t); [BELOW]
3717 // T* operator-(T*, ptrdiff_t);
3718 // T* operator+(ptrdiff_t, T*);
3719 // T& operator[](ptrdiff_t, T*); [BELOW]
3720 //
3721 // C++ [over.built]p14:
3722 //
3723 // For every T, where T is a pointer to object type, there
3724 // exist candidate operator functions of the form
3725 //
3726 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003727 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003728 = CandidateTypes.pointer_begin();
3729 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3730 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3731
3732 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3733 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3734
3735 if (Op == OO_Plus) {
3736 // T* operator+(ptrdiff_t, T*);
3737 ParamTypes[0] = ParamTypes[1];
3738 ParamTypes[1] = *Ptr;
3739 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3740 } else {
3741 // ptrdiff_t operator-(T, T);
3742 ParamTypes[1] = *Ptr;
3743 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3744 Args, 2, CandidateSet);
3745 }
3746 }
3747 }
3748 // Fall through
3749
Douglas Gregora11693b2008-11-12 17:17:38 +00003750 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003751 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003752 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003753 // C++ [over.built]p12:
3754 //
3755 // For every pair of promoted arithmetic types L and R, there
3756 // exist candidate operator functions of the form
3757 //
3758 // LR operator*(L, R);
3759 // LR operator/(L, R);
3760 // LR operator+(L, R);
3761 // LR operator-(L, R);
3762 // bool operator<(L, R);
3763 // bool operator>(L, R);
3764 // bool operator<=(L, R);
3765 // bool operator>=(L, R);
3766 // bool operator==(L, R);
3767 // bool operator!=(L, R);
3768 //
3769 // where LR is the result of the usual arithmetic conversions
3770 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003771 //
3772 // C++ [over.built]p24:
3773 //
3774 // For every pair of promoted arithmetic types L and R, there exist
3775 // candidate operator functions of the form
3776 //
3777 // LR operator?(bool, L, R);
3778 //
3779 // where LR is the result of the usual arithmetic conversions
3780 // between types L and R.
3781 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003782 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003783 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003784 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003785 Right < LastPromotedArithmeticType; ++Right) {
3786 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003787 QualType Result
3788 = isComparison
3789 ? Context.BoolTy
3790 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003791 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3792 }
3793 }
3794 break;
3795
3796 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003797 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003798 case OO_Caret:
3799 case OO_Pipe:
3800 case OO_LessLess:
3801 case OO_GreaterGreater:
3802 // C++ [over.built]p17:
3803 //
3804 // For every pair of promoted integral types L and R, there
3805 // exist candidate operator functions of the form
3806 //
3807 // LR operator%(L, R);
3808 // LR operator&(L, R);
3809 // LR operator^(L, R);
3810 // LR operator|(L, R);
3811 // L operator<<(L, R);
3812 // L operator>>(L, R);
3813 //
3814 // where LR is the result of the usual arithmetic conversions
3815 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003816 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003817 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003818 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003819 Right < LastPromotedIntegralType; ++Right) {
3820 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3821 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3822 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003823 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003824 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3825 }
3826 }
3827 break;
3828
3829 case OO_Equal:
3830 // C++ [over.built]p20:
3831 //
3832 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003833 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003834 // empty, there exist candidate operator functions of the form
3835 //
3836 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003837 for (BuiltinCandidateTypeSet::iterator
3838 Enum = CandidateTypes.enumeration_begin(),
3839 EnumEnd = CandidateTypes.enumeration_end();
3840 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003841 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003842 CandidateSet);
3843 for (BuiltinCandidateTypeSet::iterator
3844 MemPtr = CandidateTypes.member_pointer_begin(),
3845 MemPtrEnd = CandidateTypes.member_pointer_end();
3846 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003847 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003848 CandidateSet);
3849 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003850
3851 case OO_PlusEqual:
3852 case OO_MinusEqual:
3853 // C++ [over.built]p19:
3854 //
3855 // For every pair (T, VQ), where T is any type and VQ is either
3856 // volatile or empty, there exist candidate operator functions
3857 // of the form
3858 //
3859 // T*VQ& operator=(T*VQ&, T*);
3860 //
3861 // C++ [over.built]p21:
3862 //
3863 // For every pair (T, VQ), where T is a cv-qualified or
3864 // cv-unqualified object type and VQ is either volatile or
3865 // empty, there exist candidate operator functions of the form
3866 //
3867 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3868 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3869 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3870 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3871 QualType ParamTypes[2];
3872 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3873
3874 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003875 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003876 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3877 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003878
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003879 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3880 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003881 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003882 ParamTypes[0]
3883 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003884 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3885 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003886 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003887 }
3888 // Fall through.
3889
3890 case OO_StarEqual:
3891 case OO_SlashEqual:
3892 // C++ [over.built]p18:
3893 //
3894 // For every triple (L, VQ, R), where L is an arithmetic type,
3895 // VQ is either volatile or empty, and R is a promoted
3896 // arithmetic type, there exist candidate operator functions of
3897 // the form
3898 //
3899 // VQ L& operator=(VQ L&, R);
3900 // VQ L& operator*=(VQ L&, R);
3901 // VQ L& operator/=(VQ L&, R);
3902 // VQ L& operator+=(VQ L&, R);
3903 // VQ L& operator-=(VQ L&, R);
3904 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003905 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003906 Right < LastPromotedArithmeticType; ++Right) {
3907 QualType ParamTypes[2];
3908 ParamTypes[1] = ArithmeticTypes[Right];
3909
3910 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003911 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003912 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3913 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003914
3915 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003916 if (VisibleTypeConversionsQuals.hasVolatile()) {
3917 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3918 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3919 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3920 /*IsAssigmentOperator=*/Op == OO_Equal);
3921 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003922 }
3923 }
3924 break;
3925
3926 case OO_PercentEqual:
3927 case OO_LessLessEqual:
3928 case OO_GreaterGreaterEqual:
3929 case OO_AmpEqual:
3930 case OO_CaretEqual:
3931 case OO_PipeEqual:
3932 // C++ [over.built]p22:
3933 //
3934 // For every triple (L, VQ, R), where L is an integral type, VQ
3935 // is either volatile or empty, and R is a promoted integral
3936 // type, there exist candidate operator functions of the form
3937 //
3938 // VQ L& operator%=(VQ L&, R);
3939 // VQ L& operator<<=(VQ L&, R);
3940 // VQ L& operator>>=(VQ L&, R);
3941 // VQ L& operator&=(VQ L&, R);
3942 // VQ L& operator^=(VQ L&, R);
3943 // VQ L& operator|=(VQ L&, R);
3944 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003945 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003946 Right < LastPromotedIntegralType; ++Right) {
3947 QualType ParamTypes[2];
3948 ParamTypes[1] = ArithmeticTypes[Right];
3949
3950 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003951 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003952 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003953 if (VisibleTypeConversionsQuals.hasVolatile()) {
3954 // Add this built-in operator as a candidate (VQ is 'volatile').
3955 ParamTypes[0] = ArithmeticTypes[Left];
3956 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3957 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3958 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3959 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003960 }
3961 }
3962 break;
3963
Douglas Gregord08452f2008-11-19 15:42:04 +00003964 case OO_Exclaim: {
3965 // C++ [over.operator]p23:
3966 //
3967 // There also exist candidate operator functions of the form
3968 //
Mike Stump11289f42009-09-09 15:08:12 +00003969 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003970 // bool operator&&(bool, bool); [BELOW]
3971 // bool operator||(bool, bool); [BELOW]
3972 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003973 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3974 /*IsAssignmentOperator=*/false,
3975 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003976 break;
3977 }
3978
Douglas Gregora11693b2008-11-12 17:17:38 +00003979 case OO_AmpAmp:
3980 case OO_PipePipe: {
3981 // C++ [over.operator]p23:
3982 //
3983 // There also exist candidate operator functions of the form
3984 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003985 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003986 // bool operator&&(bool, bool);
3987 // bool operator||(bool, bool);
3988 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003989 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3990 /*IsAssignmentOperator=*/false,
3991 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003992 break;
3993 }
3994
3995 case OO_Subscript:
3996 // C++ [over.built]p13:
3997 //
3998 // For every cv-qualified or cv-unqualified object type T there
3999 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004000 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004001 // T* operator+(T*, ptrdiff_t); [ABOVE]
4002 // T& operator[](T*, ptrdiff_t);
4003 // T* operator-(T*, ptrdiff_t); [ABOVE]
4004 // T* operator+(ptrdiff_t, T*); [ABOVE]
4005 // T& operator[](ptrdiff_t, T*);
4006 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4007 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4008 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004009 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004010 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004011
4012 // T& operator[](T*, ptrdiff_t)
4013 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4014
4015 // T& operator[](ptrdiff_t, T*);
4016 ParamTypes[0] = ParamTypes[1];
4017 ParamTypes[1] = *Ptr;
4018 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4019 }
4020 break;
4021
4022 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004023 // C++ [over.built]p11:
4024 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4025 // C1 is the same type as C2 or is a derived class of C2, T is an object
4026 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4027 // there exist candidate operator functions of the form
4028 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4029 // where CV12 is the union of CV1 and CV2.
4030 {
4031 for (BuiltinCandidateTypeSet::iterator Ptr =
4032 CandidateTypes.pointer_begin();
4033 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4034 QualType C1Ty = (*Ptr);
4035 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004036 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004037 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004038 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004039 if (!isa<RecordType>(C1))
4040 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004041 // heuristic to reduce number of builtin candidates in the set.
4042 // Add volatile/restrict version only if there are conversions to a
4043 // volatile/restrict type.
4044 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4045 continue;
4046 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4047 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004048 }
4049 for (BuiltinCandidateTypeSet::iterator
4050 MemPtr = CandidateTypes.member_pointer_begin(),
4051 MemPtrEnd = CandidateTypes.member_pointer_end();
4052 MemPtr != MemPtrEnd; ++MemPtr) {
4053 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4054 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004055 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004056 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4057 break;
4058 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4059 // build CV12 T&
4060 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004061 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4062 T.isVolatileQualified())
4063 continue;
4064 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4065 T.isRestrictQualified())
4066 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004067 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004068 QualType ResultTy = Context.getLValueReferenceType(T);
4069 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4070 }
4071 }
4072 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004073 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004074
4075 case OO_Conditional:
4076 // Note that we don't consider the first argument, since it has been
4077 // contextually converted to bool long ago. The candidates below are
4078 // therefore added as binary.
4079 //
4080 // C++ [over.built]p24:
4081 // For every type T, where T is a pointer or pointer-to-member type,
4082 // there exist candidate operator functions of the form
4083 //
4084 // T operator?(bool, T, T);
4085 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004086 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4087 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4088 QualType ParamTypes[2] = { *Ptr, *Ptr };
4089 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4090 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004091 for (BuiltinCandidateTypeSet::iterator Ptr =
4092 CandidateTypes.member_pointer_begin(),
4093 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4094 QualType ParamTypes[2] = { *Ptr, *Ptr };
4095 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4096 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004097 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004098 }
4099}
4100
Douglas Gregore254f902009-02-04 00:32:51 +00004101/// \brief Add function candidates found via argument-dependent lookup
4102/// to the set of overloading candidates.
4103///
4104/// This routine performs argument-dependent name lookup based on the
4105/// given function name (which may also be an operator name) and adds
4106/// all of the overload candidates found by ADL to the overload
4107/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004108void
Douglas Gregore254f902009-02-04 00:32:51 +00004109Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4110 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004111 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004112 OverloadCandidateSet& CandidateSet,
4113 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004114 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004115
Douglas Gregorcabea402009-09-22 15:41:20 +00004116 // FIXME: Should we be trafficking in canonical function decls throughout?
4117
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004118 // Record all of the function candidates that we've already
4119 // added to the overload set, so that we don't add those same
4120 // candidates a second time.
4121 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4122 CandEnd = CandidateSet.end();
4123 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004124 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004125 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004126 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4127 Functions.insert(FunTmpl);
4128 }
Douglas Gregore254f902009-02-04 00:32:51 +00004129
Douglas Gregorcabea402009-09-22 15:41:20 +00004130 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004131 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004132
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004133 // Erase all of the candidates we already knew about.
4134 // FIXME: This is suboptimal. Is there a better way?
4135 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4136 CandEnd = CandidateSet.end();
4137 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004138 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004139 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004140 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4141 Functions.erase(FunTmpl);
4142 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004143
4144 // For each of the ADL candidates we found, add it to the overload
4145 // set.
4146 for (FunctionSet::iterator Func = Functions.begin(),
4147 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004148 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004149 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004150 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004151 continue;
4152
4153 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4154 false, false, PartialOverloading);
4155 } else
Mike Stump11289f42009-09-09 15:08:12 +00004156 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004157 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004158 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004159 }
Douglas Gregore254f902009-02-04 00:32:51 +00004160}
4161
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004162/// isBetterOverloadCandidate - Determines whether the first overload
4163/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004164bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004165Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004166 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004167 // Define viable functions to be better candidates than non-viable
4168 // functions.
4169 if (!Cand2.Viable)
4170 return Cand1.Viable;
4171 else if (!Cand1.Viable)
4172 return false;
4173
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004174 // C++ [over.match.best]p1:
4175 //
4176 // -- if F is a static member function, ICS1(F) is defined such
4177 // that ICS1(F) is neither better nor worse than ICS1(G) for
4178 // any function G, and, symmetrically, ICS1(G) is neither
4179 // better nor worse than ICS1(F).
4180 unsigned StartArg = 0;
4181 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4182 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004183
Douglas Gregord3cb3562009-07-07 23:38:56 +00004184 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004185 // A viable function F1 is defined to be a better function than another
4186 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004187 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004188 unsigned NumArgs = Cand1.Conversions.size();
4189 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4190 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004191 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004192 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4193 Cand2.Conversions[ArgIdx])) {
4194 case ImplicitConversionSequence::Better:
4195 // Cand1 has a better conversion sequence.
4196 HasBetterConversion = true;
4197 break;
4198
4199 case ImplicitConversionSequence::Worse:
4200 // Cand1 can't be better than Cand2.
4201 return false;
4202
4203 case ImplicitConversionSequence::Indistinguishable:
4204 // Do nothing.
4205 break;
4206 }
4207 }
4208
Mike Stump11289f42009-09-09 15:08:12 +00004209 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004210 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004211 if (HasBetterConversion)
4212 return true;
4213
Mike Stump11289f42009-09-09 15:08:12 +00004214 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004215 // specialization, or, if not that,
4216 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4217 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4218 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004219
4220 // -- F1 and F2 are function template specializations, and the function
4221 // template for F1 is more specialized than the template for F2
4222 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004223 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004224 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4225 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004226 if (FunctionTemplateDecl *BetterTemplate
4227 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4228 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004229 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4230 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004231 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004232
Douglas Gregora1f013e2008-11-07 22:36:19 +00004233 // -- the context is an initialization by user-defined conversion
4234 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4235 // from the return type of F1 to the destination type (i.e.,
4236 // the type of the entity being initialized) is a better
4237 // conversion sequence than the standard conversion sequence
4238 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004239 if (Cand1.Function && Cand2.Function &&
4240 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004241 isa<CXXConversionDecl>(Cand2.Function)) {
4242 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4243 Cand2.FinalConversion)) {
4244 case ImplicitConversionSequence::Better:
4245 // Cand1 has a better conversion sequence.
4246 return true;
4247
4248 case ImplicitConversionSequence::Worse:
4249 // Cand1 can't be better than Cand2.
4250 return false;
4251
4252 case ImplicitConversionSequence::Indistinguishable:
4253 // Do nothing
4254 break;
4255 }
4256 }
4257
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004258 return false;
4259}
4260
Mike Stump11289f42009-09-09 15:08:12 +00004261/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004262/// within an overload candidate set.
4263///
4264/// \param CandidateSet the set of candidate functions.
4265///
4266/// \param Loc the location of the function name (or operator symbol) for
4267/// which overload resolution occurs.
4268///
Mike Stump11289f42009-09-09 15:08:12 +00004269/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004270/// function, Best points to the candidate function found.
4271///
4272/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004273OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4274 SourceLocation Loc,
4275 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004276 // Find the best viable function.
4277 Best = CandidateSet.end();
4278 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4279 Cand != CandidateSet.end(); ++Cand) {
4280 if (Cand->Viable) {
4281 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4282 Best = Cand;
4283 }
4284 }
4285
4286 // If we didn't find any viable functions, abort.
4287 if (Best == CandidateSet.end())
4288 return OR_No_Viable_Function;
4289
4290 // Make sure that this function is better than every other viable
4291 // function. If not, we have an ambiguity.
4292 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4293 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004294 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004295 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004296 !isBetterOverloadCandidate(*Best, *Cand)) {
4297 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004298 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004299 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004300 }
Mike Stump11289f42009-09-09 15:08:12 +00004301
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004302 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004303 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004304 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004305 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004306 return OR_Deleted;
4307
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004308 // C++ [basic.def.odr]p2:
4309 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004310 // when referred to from a potentially-evaluated expression. [Note: this
4311 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004312 // (clause 13), user-defined conversions (12.3.2), allocation function for
4313 // placement new (5.3.4), as well as non-default initialization (8.5).
4314 if (Best->Function)
4315 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004316 return OR_Success;
4317}
4318
John McCall53262c92010-01-12 02:15:36 +00004319namespace {
4320
4321enum OverloadCandidateKind {
4322 oc_function,
4323 oc_method,
4324 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004325 oc_function_template,
4326 oc_method_template,
4327 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004328 oc_implicit_default_constructor,
4329 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004330 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004331};
4332
John McCalle1ac8d12010-01-13 00:25:19 +00004333OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4334 FunctionDecl *Fn,
4335 std::string &Description) {
4336 bool isTemplate = false;
4337
4338 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4339 isTemplate = true;
4340 Description = S.getTemplateArgumentBindingsText(
4341 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4342 }
John McCallfd0b2f82010-01-06 09:43:14 +00004343
4344 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004345 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004346 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004347
John McCall53262c92010-01-12 02:15:36 +00004348 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4349 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004350 }
4351
4352 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4353 // This actually gets spelled 'candidate function' for now, but
4354 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004355 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004356 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004357
4358 assert(Meth->isCopyAssignment()
4359 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004360 return oc_implicit_copy_assignment;
4361 }
4362
John McCalle1ac8d12010-01-13 00:25:19 +00004363 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004364}
4365
4366} // end anonymous namespace
4367
4368// Notes the location of an overload candidate.
4369void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004370 std::string FnDesc;
4371 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4372 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4373 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004374}
4375
John McCall0d1da222010-01-12 00:44:57 +00004376/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4377/// "lead" diagnostic; it will be given two arguments, the source and
4378/// target types of the conversion.
4379void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4380 SourceLocation CaretLoc,
4381 const PartialDiagnostic &PDiag) {
4382 Diag(CaretLoc, PDiag)
4383 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4384 for (AmbiguousConversionSequence::const_iterator
4385 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4386 NoteOverloadCandidate(*I);
4387 }
John McCall12f97bc2010-01-08 04:41:39 +00004388}
4389
John McCall0d1da222010-01-12 00:44:57 +00004390namespace {
4391
John McCall6a61b522010-01-13 09:16:55 +00004392void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4393 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4394 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004395 assert(Cand->Function && "for now, candidate must be a function");
4396 FunctionDecl *Fn = Cand->Function;
4397
4398 // There's a conversion slot for the object argument if this is a
4399 // non-constructor method. Note that 'I' corresponds the
4400 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004401 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004402 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004403 if (I == 0)
4404 isObjectArgument = true;
4405 else
4406 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004407 }
4408
John McCalle1ac8d12010-01-13 00:25:19 +00004409 std::string FnDesc;
4410 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4411
John McCall6a61b522010-01-13 09:16:55 +00004412 Expr *FromExpr = Conv.Bad.FromExpr;
4413 QualType FromTy = Conv.Bad.getFromType();
4414 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004415
John McCall47000992010-01-14 03:28:57 +00004416 // Do some hand-waving analysis to see if the non-viability is due to a
4417 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4418 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4419 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4420 CToTy = RT->getPointeeType();
4421 else {
4422 // TODO: detect and diagnose the full richness of const mismatches.
4423 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4424 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4425 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4426 }
4427
4428 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4429 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4430 // It is dumb that we have to do this here.
4431 while (isa<ArrayType>(CFromTy))
4432 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4433 while (isa<ArrayType>(CToTy))
4434 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4435
4436 Qualifiers FromQs = CFromTy.getQualifiers();
4437 Qualifiers ToQs = CToTy.getQualifiers();
4438
4439 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4440 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4441 << (unsigned) FnKind << FnDesc
4442 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4443 << FromTy
4444 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4445 << (unsigned) isObjectArgument << I+1;
4446 return;
4447 }
4448
4449 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4450 assert(CVR && "unexpected qualifiers mismatch");
4451
4452 if (isObjectArgument) {
4453 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4454 << (unsigned) FnKind << FnDesc
4455 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4456 << FromTy << (CVR - 1);
4457 } else {
4458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4459 << (unsigned) FnKind << FnDesc
4460 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4461 << FromTy << (CVR - 1) << I+1;
4462 }
4463 return;
4464 }
4465
4466 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004467 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4468 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004469 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004470 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004471}
4472
4473void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4474 unsigned NumFormalArgs) {
4475 // TODO: treat calls to a missing default constructor as a special case
4476
4477 FunctionDecl *Fn = Cand->Function;
4478 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4479
4480 unsigned MinParams = Fn->getMinRequiredArguments();
4481
4482 // at least / at most / exactly
4483 unsigned mode, modeCount;
4484 if (NumFormalArgs < MinParams) {
4485 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4486 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4487 mode = 0; // "at least"
4488 else
4489 mode = 2; // "exactly"
4490 modeCount = MinParams;
4491 } else {
4492 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4493 if (MinParams != FnTy->getNumArgs())
4494 mode = 1; // "at most"
4495 else
4496 mode = 2; // "exactly"
4497 modeCount = FnTy->getNumArgs();
4498 }
4499
4500 std::string Description;
4501 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4502
4503 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4504 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004505}
4506
4507void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4508 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004509 FunctionDecl *Fn = Cand->Function;
4510
John McCall12f97bc2010-01-08 04:41:39 +00004511 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004512 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004513 std::string FnDesc;
4514 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004515
4516 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004517 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004518 return;
John McCall12f97bc2010-01-08 04:41:39 +00004519 }
4520
John McCalle1ac8d12010-01-13 00:25:19 +00004521 // We don't really have anything else to say about viable candidates.
4522 if (Cand->Viable) {
4523 S.NoteOverloadCandidate(Fn);
4524 return;
4525 }
John McCall0d1da222010-01-12 00:44:57 +00004526
John McCall6a61b522010-01-13 09:16:55 +00004527 switch (Cand->FailureKind) {
4528 case ovl_fail_too_many_arguments:
4529 case ovl_fail_too_few_arguments:
4530 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004531
John McCall6a61b522010-01-13 09:16:55 +00004532 case ovl_fail_bad_deduction:
4533 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004534
John McCall6a61b522010-01-13 09:16:55 +00004535 case ovl_fail_bad_conversion:
4536 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4537 if (Cand->Conversions[I].isBad())
4538 return DiagnoseBadConversion(S, Cand, I);
4539
4540 // FIXME: this currently happens when we're called from SemaInit
4541 // when user-conversion overload fails. Figure out how to handle
4542 // those conditions and diagnose them well.
4543 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004544 }
John McCalld3224162010-01-08 00:58:21 +00004545}
4546
4547void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4548 // Desugar the type of the surrogate down to a function type,
4549 // retaining as many typedefs as possible while still showing
4550 // the function type (and, therefore, its parameter types).
4551 QualType FnType = Cand->Surrogate->getConversionType();
4552 bool isLValueReference = false;
4553 bool isRValueReference = false;
4554 bool isPointer = false;
4555 if (const LValueReferenceType *FnTypeRef =
4556 FnType->getAs<LValueReferenceType>()) {
4557 FnType = FnTypeRef->getPointeeType();
4558 isLValueReference = true;
4559 } else if (const RValueReferenceType *FnTypeRef =
4560 FnType->getAs<RValueReferenceType>()) {
4561 FnType = FnTypeRef->getPointeeType();
4562 isRValueReference = true;
4563 }
4564 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4565 FnType = FnTypePtr->getPointeeType();
4566 isPointer = true;
4567 }
4568 // Desugar down to a function type.
4569 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4570 // Reconstruct the pointer/reference as appropriate.
4571 if (isPointer) FnType = S.Context.getPointerType(FnType);
4572 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4573 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4574
4575 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4576 << FnType;
4577}
4578
4579void NoteBuiltinOperatorCandidate(Sema &S,
4580 const char *Opc,
4581 SourceLocation OpLoc,
4582 OverloadCandidate *Cand) {
4583 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4584 std::string TypeStr("operator");
4585 TypeStr += Opc;
4586 TypeStr += "(";
4587 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4588 if (Cand->Conversions.size() == 1) {
4589 TypeStr += ")";
4590 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4591 } else {
4592 TypeStr += ", ";
4593 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4594 TypeStr += ")";
4595 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4596 }
4597}
4598
4599void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4600 OverloadCandidate *Cand) {
4601 unsigned NoOperands = Cand->Conversions.size();
4602 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4603 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004604 if (ICS.isBad()) break; // all meaningless after first invalid
4605 if (!ICS.isAmbiguous()) continue;
4606
4607 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4608 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004609 }
4610}
4611
John McCall3712d9e2010-01-15 23:32:50 +00004612SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4613 if (Cand->Function)
4614 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00004615 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00004616 return Cand->Surrogate->getLocation();
4617 return SourceLocation();
4618}
4619
John McCallad2587a2010-01-12 00:48:53 +00004620struct CompareOverloadCandidatesForDisplay {
4621 Sema &S;
4622 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004623
4624 bool operator()(const OverloadCandidate *L,
4625 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00004626 // Fast-path this check.
4627 if (L == R) return false;
4628
John McCall12f97bc2010-01-08 04:41:39 +00004629 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004630 if (L->Viable) {
4631 if (!R->Viable) return true;
4632
4633 // TODO: introduce a tri-valued comparison for overload
4634 // candidates. Would be more worthwhile if we had a sort
4635 // that could exploit it.
4636 if (S.isBetterOverloadCandidate(*L, *R)) return true;
4637 if (S.isBetterOverloadCandidate(*R, *L)) return false;
4638 } else if (R->Viable)
4639 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004640
John McCall3712d9e2010-01-15 23:32:50 +00004641 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004642
John McCall3712d9e2010-01-15 23:32:50 +00004643 // Criteria by which we can sort non-viable candidates:
4644 if (!L->Viable) {
4645 // 1. Arity mismatches come after other candidates.
4646 if (L->FailureKind == ovl_fail_too_many_arguments ||
4647 L->FailureKind == ovl_fail_too_few_arguments)
4648 return false;
4649 if (R->FailureKind == ovl_fail_too_many_arguments ||
4650 R->FailureKind == ovl_fail_too_few_arguments)
4651 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004652
John McCall3712d9e2010-01-15 23:32:50 +00004653 // TODO: others?
4654 }
4655
4656 // Sort everything else by location.
4657 SourceLocation LLoc = GetLocationForCandidate(L);
4658 SourceLocation RLoc = GetLocationForCandidate(R);
4659
4660 // Put candidates without locations (e.g. builtins) at the end.
4661 if (LLoc.isInvalid()) return false;
4662 if (RLoc.isInvalid()) return true;
4663
4664 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004665 }
4666};
4667
John McCalld3224162010-01-08 00:58:21 +00004668} // end anonymous namespace
4669
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004670/// PrintOverloadCandidates - When overload resolution fails, prints
4671/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004672/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004673void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004674Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004675 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004676 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004677 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004678 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004679 // Sort the candidates by viability and position. Sorting directly would
4680 // be prohibitive, so we make a set of pointers and sort those.
4681 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4682 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4683 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4684 LastCand = CandidateSet.end();
4685 Cand != LastCand; ++Cand)
4686 if (Cand->Viable || OCD == OCD_AllCandidates)
4687 Cands.push_back(Cand);
John McCallad2587a2010-01-12 00:48:53 +00004688 std::sort(Cands.begin(), Cands.end(),
4689 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004690
John McCall0d1da222010-01-12 00:44:57 +00004691 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004692
John McCall12f97bc2010-01-08 04:41:39 +00004693 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4694 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4695 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004696
John McCalld3224162010-01-08 00:58:21 +00004697 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004698 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004699 else if (Cand->IsSurrogate)
4700 NoteSurrogateCandidate(*this, Cand);
4701
4702 // This a builtin candidate. We do not, in general, want to list
4703 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004704 else if (Cand->Viable) {
4705 // Generally we only see ambiguities including viable builtin
4706 // operators if overload resolution got screwed up by an
4707 // ambiguous user-defined conversion.
4708 //
4709 // FIXME: It's quite possible for different conversions to see
4710 // different ambiguities, though.
4711 if (!ReportedAmbiguousConversions) {
4712 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4713 ReportedAmbiguousConversions = true;
4714 }
John McCalld3224162010-01-08 00:58:21 +00004715
John McCall0d1da222010-01-12 00:44:57 +00004716 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004717 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004718 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004719 }
4720}
4721
Douglas Gregorcd695e52008-11-10 20:40:00 +00004722/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4723/// an overloaded function (C++ [over.over]), where @p From is an
4724/// expression with overloaded function type and @p ToType is the type
4725/// we're trying to resolve to. For example:
4726///
4727/// @code
4728/// int f(double);
4729/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004730///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004731/// int (*pfd)(double) = f; // selects f(double)
4732/// @endcode
4733///
4734/// This routine returns the resulting FunctionDecl if it could be
4735/// resolved, and NULL otherwise. When @p Complain is true, this
4736/// routine will emit diagnostics if there is an error.
4737FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004738Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004739 bool Complain) {
4740 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004741 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004742 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004743 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004744 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004745 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004746 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004747 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004748 FunctionType = MemTypePtr->getPointeeType();
4749 IsMember = true;
4750 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004751
4752 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004753 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004754 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004755 return 0;
4756
4757 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004758
Douglas Gregorcd695e52008-11-10 20:40:00 +00004759 // C++ [over.over]p1:
4760 // [...] [Note: any redundant set of parentheses surrounding the
4761 // overloaded function name is ignored (5.1). ]
4762 Expr *OvlExpr = From->IgnoreParens();
4763
4764 // C++ [over.over]p1:
4765 // [...] The overloaded function name can be preceded by the &
4766 // operator.
4767 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4768 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4769 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4770 }
4771
Anders Carlssonb68b0282009-10-20 22:53:47 +00004772 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004773 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004774
4775 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004776
John McCall10eae182009-11-30 22:42:35 +00004777 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004778 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004779 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4780 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004781 if (UL->hasExplicitTemplateArgs()) {
4782 HasExplicitTemplateArgs = true;
4783 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4784 }
John McCall10eae182009-11-30 22:42:35 +00004785 } else if (UnresolvedMemberExpr *ME
4786 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4787 Fns.append(ME->decls_begin(), ME->decls_end());
4788 if (ME->hasExplicitTemplateArgs()) {
4789 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004790 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004791 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004792 }
Mike Stump11289f42009-09-09 15:08:12 +00004793
John McCalld14a8642009-11-21 08:51:07 +00004794 // If we didn't actually find anything, we're done.
4795 if (Fns.empty())
4796 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004797
Douglas Gregorcd695e52008-11-10 20:40:00 +00004798 // Look through all of the overloaded functions, searching for one
4799 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004800 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004801 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004802 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4803 E = Fns.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004804 // Look through any using declarations to find the underlying function.
4805 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4806
Douglas Gregorcd695e52008-11-10 20:40:00 +00004807 // C++ [over.over]p3:
4808 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004809 // targets of type "pointer-to-function" or "reference-to-function."
4810 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004811 // type "pointer-to-member-function."
4812 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004813
Mike Stump11289f42009-09-09 15:08:12 +00004814 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004815 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00004816 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004817 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004818 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004819 // static when converting to member pointer.
4820 if (Method->isStatic() == IsMember)
4821 continue;
4822 } else if (IsMember)
4823 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004824
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004825 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004826 // If the name is a function template, template argument deduction is
4827 // done (14.8.2.2), and if the argument deduction succeeds, the
4828 // resulting template argument list is used to generate a single
4829 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004830 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004831 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004832 FunctionDecl *Specialization = 0;
4833 TemplateDeductionInfo Info(Context);
4834 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004835 = DeduceTemplateArguments(FunctionTemplate,
4836 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004837 FunctionType, Specialization, Info)) {
4838 // FIXME: make a note of the failed deduction for diagnostics.
4839 (void)Result;
4840 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004841 // FIXME: If the match isn't exact, shouldn't we just drop this as
4842 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004843 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004844 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004845 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004846 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004847 }
John McCalld14a8642009-11-21 08:51:07 +00004848
4849 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004850 }
Mike Stump11289f42009-09-09 15:08:12 +00004851
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004852 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004853 // Skip non-static functions when converting to pointer, and static
4854 // when converting to member pointer.
4855 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004856 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004857
4858 // If we have explicit template arguments, skip non-templates.
4859 if (HasExplicitTemplateArgs)
4860 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004861 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004862 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004863
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004864 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004865 QualType ResultTy;
4866 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4867 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4868 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004869 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004870 FoundNonTemplateFunction = true;
4871 }
Mike Stump11289f42009-09-09 15:08:12 +00004872 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004873 }
4874
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004875 // If there were 0 or 1 matches, we're done.
4876 if (Matches.empty())
4877 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004878 else if (Matches.size() == 1) {
4879 FunctionDecl *Result = *Matches.begin();
4880 MarkDeclarationReferenced(From->getLocStart(), Result);
4881 return Result;
4882 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004883
4884 // C++ [over.over]p4:
4885 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004886 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004887 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004888 // [...] and any given function template specialization F1 is
4889 // eliminated if the set contains a second function template
4890 // specialization whose function template is more specialized
4891 // than the function template of F1 according to the partial
4892 // ordering rules of 14.5.5.2.
4893
4894 // The algorithm specified above is quadratic. We instead use a
4895 // two-pass algorithm (similar to the one used to identify the
4896 // best viable function in an overload set) that identifies the
4897 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004898 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004899 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004900 FunctionDecl *Result =
4901 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4902 TPOC_Other, From->getLocStart(),
4903 PDiag(),
4904 PDiag(diag::err_addr_ovl_ambiguous)
4905 << TemplateMatches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00004906 PDiag(diag::note_ovl_candidate)
4907 << (unsigned) oc_function_template);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004908 MarkDeclarationReferenced(From->getLocStart(), Result);
4909 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004910 }
Mike Stump11289f42009-09-09 15:08:12 +00004911
Douglas Gregorfae1d712009-09-26 03:56:17 +00004912 // [...] any function template specializations in the set are
4913 // eliminated if the set also contains a non-template function, [...]
4914 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4915 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4916 if ((*M)->getPrimaryTemplate() == 0)
4917 RemainingMatches.push_back(*M);
4918
Mike Stump11289f42009-09-09 15:08:12 +00004919 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004920 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004921 if (RemainingMatches.size() == 1) {
4922 FunctionDecl *Result = RemainingMatches.front();
4923 MarkDeclarationReferenced(From->getLocStart(), Result);
4924 return Result;
4925 }
Mike Stump11289f42009-09-09 15:08:12 +00004926
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004927 // FIXME: We should probably return the same thing that BestViableFunction
4928 // returns (even if we issue the diagnostics here).
4929 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4930 << RemainingMatches[0]->getDeclName();
4931 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
John McCallfd0b2f82010-01-06 09:43:14 +00004932 NoteOverloadCandidate(RemainingMatches[I]);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004933 return 0;
4934}
4935
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004936/// \brief Given an expression that refers to an overloaded function, try to
4937/// resolve that overloaded function expression down to a single function.
4938///
4939/// This routine can only resolve template-ids that refer to a single function
4940/// template, where that template-id refers to a single template whose template
4941/// arguments are either provided by the template-id or have defaults,
4942/// as described in C++0x [temp.arg.explicit]p3.
4943FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
4944 // C++ [over.over]p1:
4945 // [...] [Note: any redundant set of parentheses surrounding the
4946 // overloaded function name is ignored (5.1). ]
4947 Expr *OvlExpr = From->IgnoreParens();
4948
4949 // C++ [over.over]p1:
4950 // [...] The overloaded function name can be preceded by the &
4951 // operator.
4952 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4953 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4954 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4955 }
4956
4957 bool HasExplicitTemplateArgs = false;
4958 TemplateArgumentListInfo ExplicitTemplateArgs;
4959
4960 llvm::SmallVector<NamedDecl*,8> Fns;
4961
4962 // Look into the overloaded expression.
4963 if (UnresolvedLookupExpr *UL
4964 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4965 Fns.append(UL->decls_begin(), UL->decls_end());
4966 if (UL->hasExplicitTemplateArgs()) {
4967 HasExplicitTemplateArgs = true;
4968 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4969 }
4970 } else if (UnresolvedMemberExpr *ME
4971 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4972 Fns.append(ME->decls_begin(), ME->decls_end());
4973 if (ME->hasExplicitTemplateArgs()) {
4974 HasExplicitTemplateArgs = true;
4975 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4976 }
4977 }
4978
4979 // If we didn't actually find any template-ids, we're done.
4980 if (Fns.empty() || !HasExplicitTemplateArgs)
4981 return 0;
4982
4983 // Look through all of the overloaded functions, searching for one
4984 // whose type matches exactly.
4985 FunctionDecl *Matched = 0;
4986 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4987 E = Fns.end(); I != E; ++I) {
4988 // C++0x [temp.arg.explicit]p3:
4989 // [...] In contexts where deduction is done and fails, or in contexts
4990 // where deduction is not done, if a template argument list is
4991 // specified and it, along with any default template arguments,
4992 // identifies a single function template specialization, then the
4993 // template-id is an lvalue for the function template specialization.
4994 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
4995
4996 // C++ [over.over]p2:
4997 // If the name is a function template, template argument deduction is
4998 // done (14.8.2.2), and if the argument deduction succeeds, the
4999 // resulting template argument list is used to generate a single
5000 // function template specialization, which is added to the set of
5001 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005002 FunctionDecl *Specialization = 0;
5003 TemplateDeductionInfo Info(Context);
5004 if (TemplateDeductionResult Result
5005 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5006 Specialization, Info)) {
5007 // FIXME: make a note of the failed deduction for diagnostics.
5008 (void)Result;
5009 continue;
5010 }
5011
5012 // Multiple matches; we can't resolve to a single declaration.
5013 if (Matched)
5014 return 0;
5015
5016 Matched = Specialization;
5017 }
5018
5019 return Matched;
5020}
5021
Douglas Gregorcabea402009-09-22 15:41:20 +00005022/// \brief Add a single candidate to the overload set.
5023static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00005024 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00005025 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005026 Expr **Args, unsigned NumArgs,
5027 OverloadCandidateSet &CandidateSet,
5028 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005029 if (isa<UsingShadowDecl>(Callee))
5030 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5031
Douglas Gregorcabea402009-09-22 15:41:20 +00005032 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005033 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00005034 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
5035 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005036 return;
John McCalld14a8642009-11-21 08:51:07 +00005037 }
5038
5039 if (FunctionTemplateDecl *FuncTemplate
5040 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005041 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005042 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005043 return;
5044 }
5045
5046 assert(false && "unhandled case in overloaded call candidate");
5047
5048 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005049}
5050
5051/// \brief Add the overload candidates named by callee and/or found by argument
5052/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005053void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005054 Expr **Args, unsigned NumArgs,
5055 OverloadCandidateSet &CandidateSet,
5056 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005057
5058#ifndef NDEBUG
5059 // Verify that ArgumentDependentLookup is consistent with the rules
5060 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005061 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005062 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5063 // and let Y be the lookup set produced by argument dependent
5064 // lookup (defined as follows). If X contains
5065 //
5066 // -- a declaration of a class member, or
5067 //
5068 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005069 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005070 //
5071 // -- a declaration that is neither a function or a function
5072 // template
5073 //
5074 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005075
John McCall57500772009-12-16 12:17:52 +00005076 if (ULE->requiresADL()) {
5077 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5078 E = ULE->decls_end(); I != E; ++I) {
5079 assert(!(*I)->getDeclContext()->isRecord());
5080 assert(isa<UsingShadowDecl>(*I) ||
5081 !(*I)->getDeclContext()->isFunctionOrMethod());
5082 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005083 }
5084 }
5085#endif
5086
John McCall57500772009-12-16 12:17:52 +00005087 // It would be nice to avoid this copy.
5088 TemplateArgumentListInfo TABuffer;
5089 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5090 if (ULE->hasExplicitTemplateArgs()) {
5091 ULE->copyTemplateArgumentsInto(TABuffer);
5092 ExplicitTemplateArgs = &TABuffer;
5093 }
5094
5095 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5096 E = ULE->decls_end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00005097 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005098 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005099 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005100
John McCall57500772009-12-16 12:17:52 +00005101 if (ULE->requiresADL())
5102 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005103 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005104 CandidateSet,
5105 PartialOverloading);
5106}
John McCalld681c392009-12-16 08:11:27 +00005107
John McCall57500772009-12-16 12:17:52 +00005108static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5109 Expr **Args, unsigned NumArgs) {
5110 Fn->Destroy(SemaRef.Context);
5111 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5112 Args[Arg]->Destroy(SemaRef.Context);
5113 return SemaRef.ExprError();
5114}
5115
John McCalld681c392009-12-16 08:11:27 +00005116/// Attempts to recover from a call where no functions were found.
5117///
5118/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005119static Sema::OwningExprResult
5120BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5121 UnresolvedLookupExpr *ULE,
5122 SourceLocation LParenLoc,
5123 Expr **Args, unsigned NumArgs,
5124 SourceLocation *CommaLocs,
5125 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005126
5127 CXXScopeSpec SS;
5128 if (ULE->getQualifier()) {
5129 SS.setScopeRep(ULE->getQualifier());
5130 SS.setRange(ULE->getQualifierRange());
5131 }
5132
John McCall57500772009-12-16 12:17:52 +00005133 TemplateArgumentListInfo TABuffer;
5134 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5135 if (ULE->hasExplicitTemplateArgs()) {
5136 ULE->copyTemplateArgumentsInto(TABuffer);
5137 ExplicitTemplateArgs = &TABuffer;
5138 }
5139
John McCalld681c392009-12-16 08:11:27 +00005140 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5141 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005142 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005143 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005144
John McCall57500772009-12-16 12:17:52 +00005145 assert(!R.empty() && "lookup results empty despite recovery");
5146
5147 // Build an implicit member call if appropriate. Just drop the
5148 // casts and such from the call, we don't really care.
5149 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5150 if ((*R.begin())->isCXXClassMember())
5151 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5152 else if (ExplicitTemplateArgs)
5153 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5154 else
5155 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5156
5157 if (NewFn.isInvalid())
5158 return Destroy(SemaRef, Fn, Args, NumArgs);
5159
5160 Fn->Destroy(SemaRef.Context);
5161
5162 // This shouldn't cause an infinite loop because we're giving it
5163 // an expression with non-empty lookup results, which should never
5164 // end up here.
5165 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5166 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5167 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005168}
Douglas Gregorcabea402009-09-22 15:41:20 +00005169
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005170/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005171/// (which eventually refers to the declaration Func) and the call
5172/// arguments Args/NumArgs, attempt to resolve the function call down
5173/// to a specific function. If overload resolution succeeds, returns
5174/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005175/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005176/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005177Sema::OwningExprResult
5178Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5179 SourceLocation LParenLoc,
5180 Expr **Args, unsigned NumArgs,
5181 SourceLocation *CommaLocs,
5182 SourceLocation RParenLoc) {
5183#ifndef NDEBUG
5184 if (ULE->requiresADL()) {
5185 // To do ADL, we must have found an unqualified name.
5186 assert(!ULE->getQualifier() && "qualified name with ADL");
5187
5188 // We don't perform ADL for implicit declarations of builtins.
5189 // Verify that this was correctly set up.
5190 FunctionDecl *F;
5191 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5192 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5193 F->getBuiltinID() && F->isImplicit())
5194 assert(0 && "performing ADL for builtin");
5195
5196 // We don't perform ADL in C.
5197 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5198 }
5199#endif
5200
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005201 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005202
John McCall57500772009-12-16 12:17:52 +00005203 // Add the functions denoted by the callee to the set of candidate
5204 // functions, including those from argument-dependent lookup.
5205 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005206
5207 // If we found nothing, try to recover.
5208 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5209 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005210 if (CandidateSet.empty())
5211 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5212 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005213
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005214 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005215 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005216 case OR_Success: {
5217 FunctionDecl *FDecl = Best->Function;
5218 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5219 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5220 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005221
5222 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005223 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005224 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005225 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005226 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005227 break;
5228
5229 case OR_Ambiguous:
5230 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005231 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005232 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005233 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005234
5235 case OR_Deleted:
5236 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5237 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005238 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005239 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005240 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005241 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005242 }
5243
5244 // Overload resolution failed. Destroy all of the subexpressions and
5245 // return NULL.
5246 Fn->Destroy(Context);
5247 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5248 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005249 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005250}
5251
John McCall283b9012009-11-22 00:44:51 +00005252static bool IsOverloaded(const Sema::FunctionSet &Functions) {
5253 return Functions.size() > 1 ||
5254 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5255}
5256
Douglas Gregor084d8552009-03-13 23:49:33 +00005257/// \brief Create a unary operation that may resolve to an overloaded
5258/// operator.
5259///
5260/// \param OpLoc The location of the operator itself (e.g., '*').
5261///
5262/// \param OpcIn The UnaryOperator::Opcode that describes this
5263/// operator.
5264///
5265/// \param Functions The set of non-member functions that will be
5266/// considered by overload resolution. The caller needs to build this
5267/// set based on the context using, e.g.,
5268/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5269/// set should not contain any member functions; those will be added
5270/// by CreateOverloadedUnaryOp().
5271///
5272/// \param input The input argument.
5273Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
5274 unsigned OpcIn,
5275 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00005276 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005277 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5278 Expr *Input = (Expr *)input.get();
5279
5280 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5281 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5282 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5283
5284 Expr *Args[2] = { Input, 0 };
5285 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005286
Douglas Gregor084d8552009-03-13 23:49:33 +00005287 // For post-increment and post-decrement, add the implicit '0' as
5288 // the second argument, so that we know this is a post-increment or
5289 // post-decrement.
5290 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5291 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005292 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005293 SourceLocation());
5294 NumArgs = 2;
5295 }
5296
5297 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00005298 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005299 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5300 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005301 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00005302 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00005303 FuncEnd = Functions.end();
5304 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005305 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005306
Douglas Gregor084d8552009-03-13 23:49:33 +00005307 input.release();
5308 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5309 &Args[0], NumArgs,
5310 Context.DependentTy,
5311 OpLoc));
5312 }
5313
5314 // Build an empty overload set.
5315 OverloadCandidateSet CandidateSet;
5316
5317 // Add the candidates from the given function set.
5318 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
5319
5320 // Add operator candidates that are member functions.
5321 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5322
5323 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005324 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005325
5326 // Perform overload resolution.
5327 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005328 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005329 case OR_Success: {
5330 // We found a built-in operator or an overloaded operator.
5331 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005332
Douglas Gregor084d8552009-03-13 23:49:33 +00005333 if (FnDecl) {
5334 // We matched an overloaded operator. Build a call to that
5335 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005336
Douglas Gregor084d8552009-03-13 23:49:33 +00005337 // Convert the arguments.
5338 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5339 if (PerformObjectArgumentInitialization(Input, Method))
5340 return ExprError();
5341 } else {
5342 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005343 OwningExprResult InputInit
5344 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005345 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005346 SourceLocation(),
5347 move(input));
5348 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005349 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005350
Douglas Gregore6600372009-12-23 17:40:29 +00005351 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005352 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005353 }
5354
5355 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005356 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005357
Douglas Gregor084d8552009-03-13 23:49:33 +00005358 // Build the actual expression node.
5359 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5360 SourceLocation());
5361 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005362
Douglas Gregor084d8552009-03-13 23:49:33 +00005363 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005364 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005365 ExprOwningPtr<CallExpr> TheCall(this,
5366 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005367 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005368
5369 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5370 FnDecl))
5371 return ExprError();
5372
5373 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005374 } else {
5375 // We matched a built-in operator. Convert the arguments, then
5376 // break out so that we will build the appropriate built-in
5377 // operator node.
5378 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005379 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005380 return ExprError();
5381
5382 break;
5383 }
5384 }
5385
5386 case OR_No_Viable_Function:
5387 // No viable function; fall through to handling this as a
5388 // built-in operator, which will produce an error message for us.
5389 break;
5390
5391 case OR_Ambiguous:
5392 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5393 << UnaryOperator::getOpcodeStr(Opc)
5394 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005395 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005396 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005397 return ExprError();
5398
5399 case OR_Deleted:
5400 Diag(OpLoc, diag::err_ovl_deleted_oper)
5401 << Best->Function->isDeleted()
5402 << UnaryOperator::getOpcodeStr(Opc)
5403 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005404 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005405 return ExprError();
5406 }
5407
5408 // Either we found no viable overloaded operator or we matched a
5409 // built-in operator. In either case, fall through to trying to
5410 // build a built-in operation.
5411 input.release();
5412 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5413}
5414
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005415/// \brief Create a binary operation that may resolve to an overloaded
5416/// operator.
5417///
5418/// \param OpLoc The location of the operator itself (e.g., '+').
5419///
5420/// \param OpcIn The BinaryOperator::Opcode that describes this
5421/// operator.
5422///
5423/// \param Functions The set of non-member functions that will be
5424/// considered by overload resolution. The caller needs to build this
5425/// set based on the context using, e.g.,
5426/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5427/// set should not contain any member functions; those will be added
5428/// by CreateOverloadedBinOp().
5429///
5430/// \param LHS Left-hand argument.
5431/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005432Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005433Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005434 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005435 FunctionSet &Functions,
5436 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005437 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005438 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005439
5440 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5441 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5442 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5443
5444 // If either side is type-dependent, create an appropriate dependent
5445 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005446 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005447 if (Functions.empty()) {
5448 // If there are no functions to store, just build a dependent
5449 // BinaryOperator or CompoundAssignment.
5450 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5451 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5452 Context.DependentTy, OpLoc));
5453
5454 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5455 Context.DependentTy,
5456 Context.DependentTy,
5457 Context.DependentTy,
5458 OpLoc));
5459 }
5460
John McCalld14a8642009-11-21 08:51:07 +00005461 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005462 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5463 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005464 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00005465
Mike Stump11289f42009-09-09 15:08:12 +00005466 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005467 FuncEnd = Functions.end();
5468 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005469 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005470
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005471 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005472 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005473 Context.DependentTy,
5474 OpLoc));
5475 }
5476
5477 // If this is the .* operator, which is not overloadable, just
5478 // create a built-in binary operator.
5479 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005480 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005481
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005482 // If this is the assignment operator, we only perform overload resolution
5483 // if the left-hand side is a class or enumeration type. This is actually
5484 // a hack. The standard requires that we do overload resolution between the
5485 // various built-in candidates, but as DR507 points out, this can lead to
5486 // problems. So we do it this way, which pretty much follows what GCC does.
5487 // Note that we go the traditional code path for compound assignment forms.
5488 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005489 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005490
Douglas Gregor084d8552009-03-13 23:49:33 +00005491 // Build an empty overload set.
5492 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005493
5494 // Add the candidates from the given function set.
5495 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5496
5497 // Add operator candidates that are member functions.
5498 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5499
5500 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005501 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005502
5503 // Perform overload resolution.
5504 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005505 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005506 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005507 // We found a built-in operator or an overloaded operator.
5508 FunctionDecl *FnDecl = Best->Function;
5509
5510 if (FnDecl) {
5511 // We matched an overloaded operator. Build a call to that
5512 // operator.
5513
5514 // Convert the arguments.
5515 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005516 OwningExprResult Arg1
5517 = PerformCopyInitialization(
5518 InitializedEntity::InitializeParameter(
5519 FnDecl->getParamDecl(0)),
5520 SourceLocation(),
5521 Owned(Args[1]));
5522 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005523 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005524
5525 if (PerformObjectArgumentInitialization(Args[0], Method))
5526 return ExprError();
5527
5528 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005529 } else {
5530 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005531 OwningExprResult Arg0
5532 = PerformCopyInitialization(
5533 InitializedEntity::InitializeParameter(
5534 FnDecl->getParamDecl(0)),
5535 SourceLocation(),
5536 Owned(Args[0]));
5537 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005538 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005539
5540 OwningExprResult Arg1
5541 = PerformCopyInitialization(
5542 InitializedEntity::InitializeParameter(
5543 FnDecl->getParamDecl(1)),
5544 SourceLocation(),
5545 Owned(Args[1]));
5546 if (Arg1.isInvalid())
5547 return ExprError();
5548 Args[0] = LHS = Arg0.takeAs<Expr>();
5549 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005550 }
5551
5552 // Determine the result type
5553 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005554 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005555 ResultTy = ResultTy.getNonReferenceType();
5556
5557 // Build the actual expression node.
5558 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005559 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005560 UsualUnaryConversions(FnExpr);
5561
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005562 ExprOwningPtr<CXXOperatorCallExpr>
5563 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5564 Args, 2, ResultTy,
5565 OpLoc));
5566
5567 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5568 FnDecl))
5569 return ExprError();
5570
5571 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005572 } else {
5573 // We matched a built-in operator. Convert the arguments, then
5574 // break out so that we will build the appropriate built-in
5575 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005576 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005577 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005578 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005579 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005580 return ExprError();
5581
5582 break;
5583 }
5584 }
5585
Douglas Gregor66950a32009-09-30 21:46:01 +00005586 case OR_No_Viable_Function: {
5587 // C++ [over.match.oper]p9:
5588 // If the operator is the operator , [...] and there are no
5589 // viable functions, then the operator is assumed to be the
5590 // built-in operator and interpreted according to clause 5.
5591 if (Opc == BinaryOperator::Comma)
5592 break;
5593
Sebastian Redl027de2a2009-05-21 11:50:50 +00005594 // For class as left operand for assignment or compound assigment operator
5595 // do not fall through to handling in built-in, but report that no overloaded
5596 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005597 OwningExprResult Result = ExprError();
5598 if (Args[0]->getType()->isRecordType() &&
5599 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005600 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5601 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005602 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005603 } else {
5604 // No viable function; try to create a built-in operation, which will
5605 // produce an error. Then, show the non-viable candidates.
5606 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005607 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005608 assert(Result.isInvalid() &&
5609 "C++ binary operator overloading is missing candidates!");
5610 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005611 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005612 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005613 return move(Result);
5614 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005615
5616 case OR_Ambiguous:
5617 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5618 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005619 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005620 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005621 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005622 return ExprError();
5623
5624 case OR_Deleted:
5625 Diag(OpLoc, diag::err_ovl_deleted_oper)
5626 << Best->Function->isDeleted()
5627 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005628 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005629 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005630 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005631 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005632
Douglas Gregor66950a32009-09-30 21:46:01 +00005633 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005634 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005635}
5636
Sebastian Redladba46e2009-10-29 20:17:01 +00005637Action::OwningExprResult
5638Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5639 SourceLocation RLoc,
5640 ExprArg Base, ExprArg Idx) {
5641 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5642 static_cast<Expr*>(Idx.get()) };
5643 DeclarationName OpName =
5644 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5645
5646 // If either side is type-dependent, create an appropriate dependent
5647 // expression.
5648 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5649
John McCalld14a8642009-11-21 08:51:07 +00005650 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005651 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5652 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005653 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005654 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005655
5656 Base.release();
5657 Idx.release();
5658 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5659 Args, 2,
5660 Context.DependentTy,
5661 RLoc));
5662 }
5663
5664 // Build an empty overload set.
5665 OverloadCandidateSet CandidateSet;
5666
5667 // Subscript can only be overloaded as a member function.
5668
5669 // Add operator candidates that are member functions.
5670 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5671
5672 // Add builtin operator candidates.
5673 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5674
5675 // Perform overload resolution.
5676 OverloadCandidateSet::iterator Best;
5677 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5678 case OR_Success: {
5679 // We found a built-in operator or an overloaded operator.
5680 FunctionDecl *FnDecl = Best->Function;
5681
5682 if (FnDecl) {
5683 // We matched an overloaded operator. Build a call to that
5684 // operator.
5685
5686 // Convert the arguments.
5687 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5688 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5689 PerformCopyInitialization(Args[1],
5690 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005691 AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005692 return ExprError();
5693
5694 // Determine the result type
5695 QualType ResultTy
5696 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5697 ResultTy = ResultTy.getNonReferenceType();
5698
5699 // Build the actual expression node.
5700 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5701 LLoc);
5702 UsualUnaryConversions(FnExpr);
5703
5704 Base.release();
5705 Idx.release();
5706 ExprOwningPtr<CXXOperatorCallExpr>
5707 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5708 FnExpr, Args, 2,
5709 ResultTy, RLoc));
5710
5711 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5712 FnDecl))
5713 return ExprError();
5714
5715 return MaybeBindToTemporary(TheCall.release());
5716 } else {
5717 // We matched a built-in operator. Convert the arguments, then
5718 // break out so that we will build the appropriate built-in
5719 // operator node.
5720 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005721 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005722 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005723 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005724 return ExprError();
5725
5726 break;
5727 }
5728 }
5729
5730 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005731 if (CandidateSet.empty())
5732 Diag(LLoc, diag::err_ovl_no_oper)
5733 << Args[0]->getType() << /*subscript*/ 0
5734 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5735 else
5736 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5737 << Args[0]->getType()
5738 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005739 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005740 "[]", LLoc);
5741 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005742 }
5743
5744 case OR_Ambiguous:
5745 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5746 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005747 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005748 "[]", LLoc);
5749 return ExprError();
5750
5751 case OR_Deleted:
5752 Diag(LLoc, diag::err_ovl_deleted_oper)
5753 << Best->Function->isDeleted() << "[]"
5754 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005755 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005756 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005757 return ExprError();
5758 }
5759
5760 // We matched a built-in operator; build it.
5761 Base.release();
5762 Idx.release();
5763 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5764 Owned(Args[1]), RLoc);
5765}
5766
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005767/// BuildCallToMemberFunction - Build a call to a member
5768/// function. MemExpr is the expression that refers to the member
5769/// function (and includes the object parameter), Args/NumArgs are the
5770/// arguments to the function call (not including the object
5771/// parameter). The caller needs to validate that the member
5772/// expression refers to a member function or an overloaded member
5773/// function.
John McCall2d74de92009-12-01 22:10:20 +00005774Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005775Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5776 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005777 unsigned NumArgs, SourceLocation *CommaLocs,
5778 SourceLocation RParenLoc) {
5779 // Dig out the member expression. This holds both the object
5780 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005781 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5782
John McCall10eae182009-11-30 22:42:35 +00005783 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005784 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005785 if (isa<MemberExpr>(NakedMemExpr)) {
5786 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005787 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5788 } else {
5789 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005790
John McCall6e9f8f62009-12-03 04:06:58 +00005791 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005792
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005793 // Add overload candidates
5794 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005795
John McCall2d74de92009-12-01 22:10:20 +00005796 // FIXME: avoid copy.
5797 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5798 if (UnresExpr->hasExplicitTemplateArgs()) {
5799 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5800 TemplateArgs = &TemplateArgsBuffer;
5801 }
5802
John McCall10eae182009-11-30 22:42:35 +00005803 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5804 E = UnresExpr->decls_end(); I != E; ++I) {
5805
John McCall6e9f8f62009-12-03 04:06:58 +00005806 NamedDecl *Func = *I;
5807 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5808 if (isa<UsingShadowDecl>(Func))
5809 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5810
John McCall10eae182009-11-30 22:42:35 +00005811 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005812 // If explicit template arguments were provided, we can't call a
5813 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005814 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005815 continue;
5816
John McCall6e9f8f62009-12-03 04:06:58 +00005817 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5818 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005819 } else {
John McCall10eae182009-11-30 22:42:35 +00005820 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005821 ActingDC, TemplateArgs,
5822 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005823 CandidateSet,
5824 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005825 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005826 }
Mike Stump11289f42009-09-09 15:08:12 +00005827
John McCall10eae182009-11-30 22:42:35 +00005828 DeclarationName DeclName = UnresExpr->getMemberName();
5829
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005830 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005831 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005832 case OR_Success:
5833 Method = cast<CXXMethodDecl>(Best->Function);
5834 break;
5835
5836 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005837 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005838 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005839 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005840 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005841 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005842 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005843
5844 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005845 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005846 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005847 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005848 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005849 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005850
5851 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005852 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005853 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005854 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005855 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005856 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005857 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005858 }
5859
Douglas Gregor51c538b2009-11-20 19:42:02 +00005860 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005861
John McCall2d74de92009-12-01 22:10:20 +00005862 // If overload resolution picked a static member, build a
5863 // non-member call based on that function.
5864 if (Method->isStatic()) {
5865 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5866 Args, NumArgs, RParenLoc);
5867 }
5868
John McCall10eae182009-11-30 22:42:35 +00005869 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005870 }
5871
5872 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005873 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005874 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005875 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005876 Method->getResultType().getNonReferenceType(),
5877 RParenLoc));
5878
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005879 // Check for a valid return type.
5880 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5881 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005882 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005883
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005884 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005885 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005886 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005887 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005888 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005889 MemExpr->setBase(ObjectArg);
5890
5891 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005892 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005893 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005894 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005895 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005896
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005897 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005898 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005899
John McCall2d74de92009-12-01 22:10:20 +00005900 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005901}
5902
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005903/// BuildCallToObjectOfClassType - Build a call to an object of class
5904/// type (C++ [over.call.object]), which can end up invoking an
5905/// overloaded function call operator (@c operator()) or performing a
5906/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005907Sema::ExprResult
5908Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005909 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005910 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005911 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005912 SourceLocation RParenLoc) {
5913 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005914 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005915
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005916 // C++ [over.call.object]p1:
5917 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005918 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005919 // candidate functions includes at least the function call
5920 // operators of T. The function call operators of T are obtained by
5921 // ordinary lookup of the name operator() in the context of
5922 // (E).operator().
5923 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005924 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005925
5926 if (RequireCompleteType(LParenLoc, Object->getType(),
5927 PartialDiagnostic(diag::err_incomplete_object_call)
5928 << Object->getSourceRange()))
5929 return true;
5930
John McCall27b18f82009-11-17 02:14:36 +00005931 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5932 LookupQualifiedName(R, Record->getDecl());
5933 R.suppressDiagnostics();
5934
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005935 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005936 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005937 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005938 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005939 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005940
Douglas Gregorab7897a2008-11-19 22:57:39 +00005941 // C++ [over.call.object]p2:
5942 // In addition, for each conversion function declared in T of the
5943 // form
5944 //
5945 // operator conversion-type-id () cv-qualifier;
5946 //
5947 // where cv-qualifier is the same cv-qualification as, or a
5948 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005949 // denotes the type "pointer to function of (P1,...,Pn) returning
5950 // R", or the type "reference to pointer to function of
5951 // (P1,...,Pn) returning R", or the type "reference to function
5952 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005953 // is also considered as a candidate function. Similarly,
5954 // surrogate call functions are added to the set of candidate
5955 // functions for each conversion function declared in an
5956 // accessible base class provided the function is not hidden
5957 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00005958 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00005959 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00005960 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005961 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005962 NamedDecl *D = *I;
5963 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5964 if (isa<UsingShadowDecl>(D))
5965 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5966
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005967 // Skip over templated conversion functions; they aren't
5968 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005969 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005970 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005971
John McCall6e9f8f62009-12-03 04:06:58 +00005972 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005973
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005974 // Strip the reference type (if any) and then the pointer type (if
5975 // any) to get down to what might be a function type.
5976 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5977 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5978 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005979
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005980 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005981 AddSurrogateCandidate(Conv, ActingContext, Proto,
5982 Object->getType(), Args, NumArgs,
5983 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005984 }
Mike Stump11289f42009-09-09 15:08:12 +00005985
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005986 // Perform overload resolution.
5987 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005988 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005989 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005990 // Overload resolution succeeded; we'll build the appropriate call
5991 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005992 break;
5993
5994 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00005995 if (CandidateSet.empty())
5996 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
5997 << Object->getType() << /*call*/ 1
5998 << Object->getSourceRange();
5999 else
6000 Diag(Object->getSourceRange().getBegin(),
6001 diag::err_ovl_no_viable_object_call)
6002 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006003 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006004 break;
6005
6006 case OR_Ambiguous:
6007 Diag(Object->getSourceRange().getBegin(),
6008 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006009 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006010 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006011 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006012
6013 case OR_Deleted:
6014 Diag(Object->getSourceRange().getBegin(),
6015 diag::err_ovl_deleted_object_call)
6016 << Best->Function->isDeleted()
6017 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006018 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006019 break;
Mike Stump11289f42009-09-09 15:08:12 +00006020 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006021
Douglas Gregorab7897a2008-11-19 22:57:39 +00006022 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006023 // We had an error; delete all of the subexpressions and return
6024 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006025 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006026 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006027 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006028 return true;
6029 }
6030
Douglas Gregorab7897a2008-11-19 22:57:39 +00006031 if (Best->Function == 0) {
6032 // Since there is no function declaration, this is one of the
6033 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006034 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006035 = cast<CXXConversionDecl>(
6036 Best->Conversions[0].UserDefined.ConversionFunction);
6037
6038 // We selected one of the surrogate functions that converts the
6039 // object parameter to a function pointer. Perform the conversion
6040 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006041
6042 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006043 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006044 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006045
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006046 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006047 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6048 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006049 }
6050
6051 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6052 // that calls this method, using Object for the implicit object
6053 // parameter and passing along the remaining arguments.
6054 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006055 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006056
6057 unsigned NumArgsInProto = Proto->getNumArgs();
6058 unsigned NumArgsToCheck = NumArgs;
6059
6060 // Build the full argument list for the method call (the
6061 // implicit object parameter is placed at the beginning of the
6062 // list).
6063 Expr **MethodArgs;
6064 if (NumArgs < NumArgsInProto) {
6065 NumArgsToCheck = NumArgsInProto;
6066 MethodArgs = new Expr*[NumArgsInProto + 1];
6067 } else {
6068 MethodArgs = new Expr*[NumArgs + 1];
6069 }
6070 MethodArgs[0] = Object;
6071 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6072 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006073
6074 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006075 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006076 UsualUnaryConversions(NewFn);
6077
6078 // Once we've built TheCall, all of the expressions are properly
6079 // owned.
6080 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006081 ExprOwningPtr<CXXOperatorCallExpr>
6082 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006083 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006084 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006085 delete [] MethodArgs;
6086
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006087 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6088 Method))
6089 return true;
6090
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006091 // We may have default arguments. If so, we need to allocate more
6092 // slots in the call for them.
6093 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006094 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006095 else if (NumArgs > NumArgsInProto)
6096 NumArgsToCheck = NumArgsInProto;
6097
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006098 bool IsError = false;
6099
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006100 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006101 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006102 TheCall->setArg(0, Object);
6103
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006104
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006105 // Check the argument types.
6106 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006107 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006108 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006109 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006110
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006111 // Pass the argument.
6112 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006113 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006114 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006115 OwningExprResult DefArg
6116 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6117 if (DefArg.isInvalid()) {
6118 IsError = true;
6119 break;
6120 }
6121
6122 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006123 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006124
6125 TheCall->setArg(i + 1, Arg);
6126 }
6127
6128 // If this is a variadic call, handle args passed through "...".
6129 if (Proto->isVariadic()) {
6130 // Promote the arguments (C99 6.5.2.2p7).
6131 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6132 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006133 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006134 TheCall->setArg(i + 1, Arg);
6135 }
6136 }
6137
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006138 if (IsError) return true;
6139
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006140 if (CheckFunctionCall(Method, TheCall.get()))
6141 return true;
6142
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006143 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006144}
6145
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006146/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006147/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006148/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006149Sema::OwningExprResult
6150Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6151 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006152 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006153
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006154 // C++ [over.ref]p1:
6155 //
6156 // [...] An expression x->m is interpreted as (x.operator->())->m
6157 // for a class object x of type T if T::operator->() exists and if
6158 // the operator is selected as the best match function by the
6159 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006160 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6161 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006162 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006163
Eli Friedman132e70b2009-11-18 01:28:03 +00006164 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
6165 PDiag(diag::err_typecheck_incomplete_tag)
6166 << Base->getSourceRange()))
6167 return ExprError();
6168
John McCall27b18f82009-11-17 02:14:36 +00006169 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6170 LookupQualifiedName(R, BaseRecord->getDecl());
6171 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006172
6173 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006174 Oper != OperEnd; ++Oper) {
6175 NamedDecl *D = *Oper;
6176 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6177 if (isa<UsingShadowDecl>(D))
6178 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6179
6180 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
6181 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006182 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006183 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006184
6185 // Perform overload resolution.
6186 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006187 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006188 case OR_Success:
6189 // Overload resolution succeeded; we'll build the call below.
6190 break;
6191
6192 case OR_No_Viable_Function:
6193 if (CandidateSet.empty())
6194 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006195 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006196 else
6197 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006198 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006199 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006200 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006201
6202 case OR_Ambiguous:
6203 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006204 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006205 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006206 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006207
6208 case OR_Deleted:
6209 Diag(OpLoc, diag::err_ovl_deleted_oper)
6210 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006211 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006212 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006213 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006214 }
6215
6216 // Convert the object parameter.
6217 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006218 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006219 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006220
6221 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006222 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006223
6224 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006225 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6226 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006227 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006228
6229 QualType ResultTy = Method->getResultType().getNonReferenceType();
6230 ExprOwningPtr<CXXOperatorCallExpr>
6231 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6232 &Base, 1, ResultTy, OpLoc));
6233
6234 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6235 Method))
6236 return ExprError();
6237 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006238}
6239
Douglas Gregorcd695e52008-11-10 20:40:00 +00006240/// FixOverloadedFunctionReference - E is an expression that refers to
6241/// a C++ overloaded function (possibly with some parentheses and
6242/// perhaps a '&' around it). We have resolved the overloaded function
6243/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006244/// refer (possibly indirectly) to Fn. Returns the new expr.
6245Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006246 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006247 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6248 if (SubExpr == PE->getSubExpr())
6249 return PE->Retain();
6250
6251 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6252 }
6253
6254 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6255 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006256 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006257 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006258 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006259 if (SubExpr == ICE->getSubExpr())
6260 return ICE->Retain();
6261
6262 return new (Context) ImplicitCastExpr(ICE->getType(),
6263 ICE->getCastKind(),
6264 SubExpr,
6265 ICE->isLvalueCast());
6266 }
6267
6268 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006269 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006270 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006271 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6272 if (Method->isStatic()) {
6273 // Do nothing: static member functions aren't any different
6274 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006275 } else {
John McCalle66edc12009-11-24 19:00:30 +00006276 // Fix the sub expression, which really has to be an
6277 // UnresolvedLookupExpr holding an overloaded member function
6278 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006279 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6280 if (SubExpr == UnOp->getSubExpr())
6281 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006282
John McCalld14a8642009-11-21 08:51:07 +00006283 assert(isa<DeclRefExpr>(SubExpr)
6284 && "fixed to something other than a decl ref");
6285 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6286 && "fixed to a member ref with no nested name qualifier");
6287
6288 // We have taken the address of a pointer to member
6289 // function. Perform the computation here so that we get the
6290 // appropriate pointer to member type.
6291 QualType ClassType
6292 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6293 QualType MemPtrType
6294 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6295
6296 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6297 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006298 }
6299 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006300 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6301 if (SubExpr == UnOp->getSubExpr())
6302 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006303
Douglas Gregor51c538b2009-11-20 19:42:02 +00006304 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6305 Context.getPointerType(SubExpr->getType()),
6306 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006307 }
John McCalld14a8642009-11-21 08:51:07 +00006308
6309 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006310 // FIXME: avoid copy.
6311 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006312 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006313 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6314 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006315 }
6316
John McCalld14a8642009-11-21 08:51:07 +00006317 return DeclRefExpr::Create(Context,
6318 ULE->getQualifier(),
6319 ULE->getQualifierRange(),
6320 Fn,
6321 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006322 Fn->getType(),
6323 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006324 }
6325
John McCall10eae182009-11-30 22:42:35 +00006326 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006327 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006328 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6329 if (MemExpr->hasExplicitTemplateArgs()) {
6330 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6331 TemplateArgs = &TemplateArgsBuffer;
6332 }
John McCall6b51f282009-11-23 01:53:49 +00006333
John McCall2d74de92009-12-01 22:10:20 +00006334 Expr *Base;
6335
6336 // If we're filling in
6337 if (MemExpr->isImplicitAccess()) {
6338 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6339 return DeclRefExpr::Create(Context,
6340 MemExpr->getQualifier(),
6341 MemExpr->getQualifierRange(),
6342 Fn,
6343 MemExpr->getMemberLoc(),
6344 Fn->getType(),
6345 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006346 } else {
6347 SourceLocation Loc = MemExpr->getMemberLoc();
6348 if (MemExpr->getQualifier())
6349 Loc = MemExpr->getQualifierRange().getBegin();
6350 Base = new (Context) CXXThisExpr(Loc,
6351 MemExpr->getBaseType(),
6352 /*isImplicit=*/true);
6353 }
John McCall2d74de92009-12-01 22:10:20 +00006354 } else
6355 Base = MemExpr->getBase()->Retain();
6356
6357 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006358 MemExpr->isArrow(),
6359 MemExpr->getQualifier(),
6360 MemExpr->getQualifierRange(),
6361 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006362 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006363 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006364 Fn->getType());
6365 }
6366
Douglas Gregor51c538b2009-11-20 19:42:02 +00006367 assert(false && "Invalid reference to overloaded function");
6368 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006369}
6370
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006371Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6372 FunctionDecl *Fn) {
6373 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6374}
6375
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006376} // end namespace clang