blob: ca8d13517eb3c7163e377e4141fadd4ce391f1bd [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
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.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000439/// If @p UserCast, the implicit conversion is being done for a user-specified
440/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000442Sema::TryImplicitConversion(Expr* From, QualType ToType,
443 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000444 bool AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000445 bool InOverloadResolution,
446 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000448 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000449 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000450 return ICS;
451 }
452
453 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000454 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000455 return ICS;
456 }
457
458 OverloadCandidateSet Conversions(From->getExprLoc());
459 OverloadingResult UserDefResult
460 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
461 !SuppressUserConversions, AllowExplicit,
Douglas Gregor7b23e412010-04-16 17:25:05 +0000462 UserCast);
John McCallbc077cf2010-02-08 23:07:23 +0000463
464 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000465 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000466 // C++ [over.ics.user]p4:
467 // A conversion of an expression of class type to the same class
468 // type is given Exact Match rank, and a conversion of an
469 // expression of class type to a base class of that type is
470 // given Conversion rank, in spite of the fact that a copy
471 // constructor (i.e., a user-defined conversion function) is
472 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000473 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000474 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000475 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000476 = Context.getCanonicalType(From->getType().getUnqualifiedType());
477 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000478 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000479 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000480 // Turn this into a "standard" conversion sequence, so that it
481 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000482 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000483 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000484 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000485 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000486 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000487 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000488 ICS.Standard.Second = ICK_Derived_To_Base;
489 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000490 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000491
492 // C++ [over.best.ics]p4:
493 // However, when considering the argument of a user-defined
494 // conversion function that is a candidate by 13.3.1.3 when
495 // invoked for the copying of the temporary in the second step
496 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
497 // 13.3.1.6 in all cases, only standard conversion sequences and
498 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000499 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000500 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000501 }
John McCalle8c8cd22010-01-13 22:30:33 +0000502 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000503 ICS.setAmbiguous();
504 ICS.Ambiguous.setFromType(From->getType());
505 ICS.Ambiguous.setToType(ToType);
506 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
507 Cand != Conversions.end(); ++Cand)
508 if (Cand->Viable)
509 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000510 } else {
John McCall65eb8792010-02-25 01:37:24 +0000511 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000512 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000513
514 return ICS;
515}
516
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000517/// \brief Determine whether the conversion from FromType to ToType is a valid
518/// conversion that strips "noreturn" off the nested function type.
519static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
520 QualType ToType, QualType &ResultTy) {
521 if (Context.hasSameUnqualifiedType(FromType, ToType))
522 return false;
523
524 // Strip the noreturn off the type we're converting from; noreturn can
525 // safely be removed.
526 FromType = Context.getNoReturnType(FromType, false);
527 if (!Context.hasSameUnqualifiedType(FromType, ToType))
528 return false;
529
530 ResultTy = FromType;
531 return true;
532}
533
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000534/// IsStandardConversion - Determines whether there is a standard
535/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
536/// expression From to the type ToType. Standard conversion sequences
537/// only consider non-class types; for conversions that involve class
538/// types, use TryImplicitConversion. If a conversion exists, SCS will
539/// contain the standard conversion sequence required to perform this
540/// conversion and this routine will return true. Otherwise, this
541/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000542bool
543Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000544 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000545 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546 QualType FromType = From->getType();
547
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000548 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000549 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000550 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000551 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000552 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000553 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000554
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000555 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000556 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000557 if (FromType->isRecordType() || ToType->isRecordType()) {
558 if (getLangOptions().CPlusPlus)
559 return false;
560
Mike Stump11289f42009-09-09 15:08:12 +0000561 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000562 }
563
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000564 // The first conversion can be an lvalue-to-rvalue conversion,
565 // array-to-pointer conversion, or function-to-pointer conversion
566 // (C++ 4p1).
567
John McCall16df1e52010-03-30 21:47:33 +0000568 DeclAccessPair AccessPair;
569
Mike Stump11289f42009-09-09 15:08:12 +0000570 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000571 // An lvalue (3.10) of a non-function, non-array type T can be
572 // converted to an rvalue.
573 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000574 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000575 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000576 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000577 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578
579 // If T is a non-class type, the type of the rvalue is the
580 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000581 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
582 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000583 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000584 } else if (FromType->isArrayType()) {
585 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000586 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000587
588 // An lvalue or rvalue of type "array of N T" or "array of unknown
589 // bound of T" can be converted to an rvalue of type "pointer to
590 // T" (C++ 4.2p1).
591 FromType = Context.getArrayDecayedType(FromType);
592
593 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
594 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000595 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000596
597 // For the purpose of ranking in overload resolution
598 // (13.3.3.1.1), this conversion is considered an
599 // array-to-pointer conversion followed by a qualification
600 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Identity;
602 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000603 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000604 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000605 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
607 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000608 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000609
610 // An lvalue of function type T can be converted to an rvalue of
611 // type "pointer to T." The result is a pointer to the
612 // function. (C++ 4.3p1).
613 FromType = Context.getPointerType(FromType);
Douglas Gregor064fdb22010-04-14 23:11:21 +0000614 } else if (From->getType() == Context.OverloadTy) {
615 if (FunctionDecl *Fn
616 = ResolveAddressOfOverloadedFunction(From, ToType, false,
617 AccessPair)) {
618 // Address of overloaded function (C++ [over.over]).
619 SCS.First = ICK_Function_To_Pointer;
Douglas Gregorcd695e52008-11-10 20:40:00 +0000620
Douglas Gregor064fdb22010-04-14 23:11:21 +0000621 // We were able to resolve the address of the overloaded function,
622 // so we can convert to the type of that function.
623 FromType = Fn->getType();
624 if (ToType->isLValueReferenceType())
625 FromType = Context.getLValueReferenceType(FromType);
626 else if (ToType->isRValueReferenceType())
627 FromType = Context.getRValueReferenceType(FromType);
628 else if (ToType->isMemberPointerType()) {
629 // Resolve address only succeeds if both sides are member pointers,
630 // but it doesn't have to be the same class. See DR 247.
631 // Note that this means that the type of &Derived::fn can be
632 // Ret (Base::*)(Args) if the fn overload actually found is from the
633 // base class, even if it was brought into the derived class via a
634 // using declaration. The standard isn't clear on this issue at all.
635 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
636 FromType = Context.getMemberPointerType(FromType,
637 Context.getTypeDeclType(M->getParent()).getTypePtr());
638 } else {
639 FromType = Context.getPointerType(FromType);
640 }
641 } else {
642 return false;
643 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000644 } else {
645 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000646 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000647 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000648 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000649
650 // The second conversion can be an integral promotion, floating
651 // point promotion, integral conversion, floating point conversion,
652 // floating-integral conversion, pointer conversion,
653 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000654 // For overloading in C, this can also be a "compatible-type"
655 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000656 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000657 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658 // The unqualified versions of the types are the same: there's no
659 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000661 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000662 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000663 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000664 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000665 } else if (IsFloatingPointPromotion(FromType, ToType)) {
666 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000667 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000668 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000669 } else if (IsComplexPromotion(FromType, ToType)) {
670 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000671 SCS.Second = ICK_Complex_Promotion;
672 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000673 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000674 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000675 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000676 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000677 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000678 } else if (FromType->isComplexType() && ToType->isComplexType()) {
679 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000680 SCS.Second = ICK_Complex_Conversion;
681 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000682 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
683 (ToType->isComplexType() && FromType->isArithmeticType())) {
684 // Complex-real conversions (C99 6.3.1.7)
685 SCS.Second = ICK_Complex_Real;
686 FromType = ToType.getUnqualifiedType();
687 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
688 // Floating point conversions (C++ 4.8).
689 SCS.Second = ICK_Floating_Conversion;
690 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000691 } else if ((FromType->isFloatingType() &&
692 ToType->isIntegralType() && (!ToType->isBooleanType() &&
693 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000694 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000695 ToType->isFloatingType())) {
696 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000697 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000698 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000699 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
700 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000701 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000702 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000703 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000704 } else if (IsMemberPointerConversion(From, FromType, ToType,
705 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000706 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000707 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000708 } else if (ToType->isBooleanType() &&
709 (FromType->isArithmeticType() ||
710 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000711 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000712 FromType->isBlockPointerType() ||
713 FromType->isMemberPointerType() ||
714 FromType->isNullPtrType())) {
715 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000716 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000717 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000718 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000719 Context.typesAreCompatible(ToType, FromType)) {
720 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000721 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000722 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
723 // Treat a conversion that strips "noreturn" as an identity conversion.
724 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725 } else {
726 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000727 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000728 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000729 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000730
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000731 QualType CanonFrom;
732 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000733 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000734 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000735 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000736 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000737 CanonFrom = Context.getCanonicalType(FromType);
738 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739 } else {
740 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000741 SCS.Third = ICK_Identity;
742
Mike Stump11289f42009-09-09 15:08:12 +0000743 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000744 // [...] Any difference in top-level cv-qualification is
745 // subsumed by the initialization itself and does not constitute
746 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000747 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000748 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000749 if (CanonFrom.getLocalUnqualifiedType()
750 == CanonTo.getLocalUnqualifiedType() &&
751 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000752 FromType = ToType;
753 CanonFrom = CanonTo;
754 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000755 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000756 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000757
758 // If we have not converted the argument type to the parameter type,
759 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000760 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000761 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000762
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000763 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000764}
765
766/// IsIntegralPromotion - Determines whether the conversion from the
767/// expression From (whose potentially-adjusted type is FromType) to
768/// ToType is an integral promotion (C++ 4.5). If so, returns true and
769/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000770bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000771 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000772 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000773 if (!To) {
774 return false;
775 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000776
777 // An rvalue of type char, signed char, unsigned char, short int, or
778 // unsigned short int can be converted to an rvalue of type int if
779 // int can represent all the values of the source type; otherwise,
780 // the source rvalue can be converted to an rvalue of type unsigned
781 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000782 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
783 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 if (// We can promote any signed, promotable integer type to an int
785 (FromType->isSignedIntegerType() ||
786 // We can promote any unsigned integer type whose size is
787 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000788 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000789 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000790 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000791 }
792
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000793 return To->getKind() == BuiltinType::UInt;
794 }
795
796 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
797 // can be converted to an rvalue of the first of the following types
798 // that can represent all the values of its underlying type: int,
799 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000800
801 // We pre-calculate the promotion type for enum types.
802 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
803 if (ToType->isIntegerType())
804 return Context.hasSameUnqualifiedType(ToType,
805 FromEnumType->getDecl()->getPromotionType());
806
807 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000808 // Determine whether the type we're converting from is signed or
809 // unsigned.
810 bool FromIsSigned;
811 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000812
813 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
814 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000815
816 // The types we'll try to promote to, in the appropriate
817 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000818 QualType PromoteTypes[6] = {
819 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000820 Context.LongTy, Context.UnsignedLongTy ,
821 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000822 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000823 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000824 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
825 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000826 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000827 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
828 // We found the type that we can promote to. If this is the
829 // type we wanted, we have a promotion. Otherwise, no
830 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000831 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000832 }
833 }
834 }
835
836 // An rvalue for an integral bit-field (9.6) can be converted to an
837 // rvalue of type int if int can represent all the values of the
838 // bit-field; otherwise, it can be converted to unsigned int if
839 // unsigned int can represent all the values of the bit-field. If
840 // the bit-field is larger yet, no integral promotion applies to
841 // it. If the bit-field has an enumerated type, it is treated as any
842 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000843 // FIXME: We should delay checking of bit-fields until we actually perform the
844 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000845 using llvm::APSInt;
846 if (From)
847 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000848 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000849 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
850 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
851 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
852 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000853
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000854 // Are we promoting to an int from a bitfield that fits in an int?
855 if (BitWidth < ToSize ||
856 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
857 return To->getKind() == BuiltinType::Int;
858 }
Mike Stump11289f42009-09-09 15:08:12 +0000859
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000860 // Are we promoting to an unsigned int from an unsigned bitfield
861 // that fits into an unsigned int?
862 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
863 return To->getKind() == BuiltinType::UInt;
864 }
Mike Stump11289f42009-09-09 15:08:12 +0000865
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000866 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000867 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000868 }
Mike Stump11289f42009-09-09 15:08:12 +0000869
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000870 // An rvalue of type bool can be converted to an rvalue of type int,
871 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000872 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000873 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000874 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000875
876 return false;
877}
878
879/// IsFloatingPointPromotion - Determines whether the conversion from
880/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
881/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000882bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000883 /// An rvalue of type float can be converted to an rvalue of type
884 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000885 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
886 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000887 if (FromBuiltin->getKind() == BuiltinType::Float &&
888 ToBuiltin->getKind() == BuiltinType::Double)
889 return true;
890
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000891 // C99 6.3.1.5p1:
892 // When a float is promoted to double or long double, or a
893 // double is promoted to long double [...].
894 if (!getLangOptions().CPlusPlus &&
895 (FromBuiltin->getKind() == BuiltinType::Float ||
896 FromBuiltin->getKind() == BuiltinType::Double) &&
897 (ToBuiltin->getKind() == BuiltinType::LongDouble))
898 return true;
899 }
900
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000901 return false;
902}
903
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000904/// \brief Determine if a conversion is a complex promotion.
905///
906/// A complex promotion is defined as a complex -> complex conversion
907/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000908/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000909bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000910 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000911 if (!FromComplex)
912 return false;
913
John McCall9dd450b2009-09-21 23:43:11 +0000914 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000915 if (!ToComplex)
916 return false;
917
918 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000919 ToComplex->getElementType()) ||
920 IsIntegralPromotion(0, FromComplex->getElementType(),
921 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000922}
923
Douglas Gregor237f96c2008-11-26 23:31:11 +0000924/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
925/// the pointer type FromPtr to a pointer to type ToPointee, with the
926/// same type qualifiers as FromPtr has on its pointee type. ToType,
927/// if non-empty, will be a pointer to ToType that may or may not have
928/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000929static QualType
930BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000931 QualType ToPointee, QualType ToType,
932 ASTContext &Context) {
933 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
934 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000935 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000936
937 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000938 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000939 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000940 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000941 return ToType;
942
943 // Build a pointer to ToPointee. It has the right qualifiers
944 // already.
945 return Context.getPointerType(ToPointee);
946 }
947
948 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000949 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000950 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
951 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000952}
953
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000954/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
955/// the FromType, which is an objective-c pointer, to ToType, which may or may
956/// not have the right set of qualifiers.
957static QualType
958BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
959 QualType ToType,
960 ASTContext &Context) {
961 QualType CanonFromType = Context.getCanonicalType(FromType);
962 QualType CanonToType = Context.getCanonicalType(ToType);
963 Qualifiers Quals = CanonFromType.getQualifiers();
964
965 // Exact qualifier match -> return the pointer type we're converting to.
966 if (CanonToType.getLocalQualifiers() == Quals)
967 return ToType;
968
969 // Just build a canonical type that has the right qualifiers.
970 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
971}
972
Mike Stump11289f42009-09-09 15:08:12 +0000973static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000974 bool InOverloadResolution,
975 ASTContext &Context) {
976 // Handle value-dependent integral null pointer constants correctly.
977 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
978 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
979 Expr->getType()->isIntegralType())
980 return !InOverloadResolution;
981
Douglas Gregor56751b52009-09-25 04:25:58 +0000982 return Expr->isNullPointerConstant(Context,
983 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
984 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000985}
Mike Stump11289f42009-09-09 15:08:12 +0000986
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000987/// IsPointerConversion - Determines whether the conversion of the
988/// expression From, which has the (possibly adjusted) type FromType,
989/// can be converted to the type ToType via a pointer conversion (C++
990/// 4.10). If so, returns true and places the converted type (that
991/// might differ from ToType in its cv-qualifiers at some level) into
992/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000993///
Douglas Gregora29dc052008-11-27 01:19:21 +0000994/// This routine also supports conversions to and from block pointers
995/// and conversions with Objective-C's 'id', 'id<protocols...>', and
996/// pointers to interfaces. FIXME: Once we've determined the
997/// appropriate overloading rules for Objective-C, we may want to
998/// split the Objective-C checks into a different routine; however,
999/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001000/// conversions, so for now they live here. IncompatibleObjC will be
1001/// set if the conversion is an allowed Objective-C conversion that
1002/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001003bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001004 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001005 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001006 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001007 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001008 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1009 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001010
Mike Stump11289f42009-09-09 15:08:12 +00001011 // Conversion from a null pointer constant to any Objective-C pointer type.
1012 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001014 ConvertedType = ToType;
1015 return true;
1016 }
1017
Douglas Gregor231d1c62008-11-27 00:15:41 +00001018 // Blocks: Block pointers can be converted to void*.
1019 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001020 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001021 ConvertedType = ToType;
1022 return true;
1023 }
1024 // Blocks: A null pointer constant can be converted to a block
1025 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001026 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001027 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001028 ConvertedType = ToType;
1029 return true;
1030 }
1031
Sebastian Redl576fd422009-05-10 18:38:11 +00001032 // If the left-hand-side is nullptr_t, the right side can be a null
1033 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001034 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001036 ConvertedType = ToType;
1037 return true;
1038 }
1039
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001040 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001041 if (!ToTypePtr)
1042 return false;
1043
1044 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001045 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001046 ConvertedType = ToType;
1047 return true;
1048 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001049
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001050 // Beyond this point, both types need to be pointers
1051 // , including objective-c pointers.
1052 QualType ToPointeeType = ToTypePtr->getPointeeType();
1053 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1054 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1055 ToType, Context);
1056 return true;
1057
1058 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001059 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001060 if (!FromTypePtr)
1061 return false;
1062
1063 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001064
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001065 // An rvalue of type "pointer to cv T," where T is an object type,
1066 // can be converted to an rvalue of type "pointer to cv void" (C++
1067 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001068 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001069 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001070 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001071 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001072 return true;
1073 }
1074
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001075 // When we're overloading in C, we allow a special kind of pointer
1076 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001077 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001078 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001079 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001080 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001081 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001082 return true;
1083 }
1084
Douglas Gregor5c407d92008-10-23 00:40:37 +00001085 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001086 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001087 // An rvalue of type "pointer to cv D," where D is a class type,
1088 // can be converted to an rvalue of type "pointer to cv B," where
1089 // B is a base class (clause 10) of D. If B is an inaccessible
1090 // (clause 11) or ambiguous (10.2) base class of D, a program that
1091 // necessitates this conversion is ill-formed. The result of the
1092 // conversion is a pointer to the base class sub-object of the
1093 // derived class object. The null pointer value is converted to
1094 // the null pointer value of the destination type.
1095 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001096 // Note that we do not check for ambiguity or inaccessibility
1097 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001098 if (getLangOptions().CPlusPlus &&
1099 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001100 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001101 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001102 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001104 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001105 ToType, Context);
1106 return true;
1107 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001108
Douglas Gregora119f102008-12-19 19:13:09 +00001109 return false;
1110}
1111
1112/// isObjCPointerConversion - Determines whether this is an
1113/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1114/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001115bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001116 QualType& ConvertedType,
1117 bool &IncompatibleObjC) {
1118 if (!getLangOptions().ObjC1)
1119 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001120
Steve Naroff7cae42b2009-07-10 23:34:53 +00001121 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001122 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001123 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001124 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001125
Steve Naroff7cae42b2009-07-10 23:34:53 +00001126 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001127 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001128 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001129 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001130 ConvertedType = ToType;
1131 return true;
1132 }
1133 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001134 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001135 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001136 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001137 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001138 ConvertedType = ToType;
1139 return true;
1140 }
1141 // Objective C++: We're able to convert from a pointer to an
1142 // interface to a pointer to a different interface.
1143 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001144 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1145 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1146 if (getLangOptions().CPlusPlus && LHS && RHS &&
1147 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1148 FromObjCPtr->getPointeeType()))
1149 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001150 ConvertedType = ToType;
1151 return true;
1152 }
1153
1154 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1155 // Okay: this is some kind of implicit downcast of Objective-C
1156 // interfaces, which is permitted. However, we're going to
1157 // complain about it.
1158 IncompatibleObjC = true;
1159 ConvertedType = FromType;
1160 return true;
1161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001163 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001164 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001165 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001166 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001167 else if (const BlockPointerType *ToBlockPtr =
1168 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001169 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001170 // to a block pointer type.
1171 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1172 ConvertedType = ToType;
1173 return true;
1174 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001175 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001176 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001177 else if (FromType->getAs<BlockPointerType>() &&
1178 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1179 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001180 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001181 ConvertedType = ToType;
1182 return true;
1183 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001184 else
Douglas Gregora119f102008-12-19 19:13:09 +00001185 return false;
1186
Douglas Gregor033f56d2008-12-23 00:53:59 +00001187 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001188 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001189 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001190 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001191 FromPointeeType = FromBlockPtr->getPointeeType();
1192 else
Douglas Gregora119f102008-12-19 19:13:09 +00001193 return false;
1194
Douglas Gregora119f102008-12-19 19:13:09 +00001195 // If we have pointers to pointers, recursively check whether this
1196 // is an Objective-C conversion.
1197 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1198 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1199 IncompatibleObjC)) {
1200 // We always complain about this conversion.
1201 IncompatibleObjC = true;
1202 ConvertedType = ToType;
1203 return true;
1204 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001205 // Allow conversion of pointee being objective-c pointer to another one;
1206 // as in I* to id.
1207 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1208 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1209 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1210 IncompatibleObjC)) {
1211 ConvertedType = ToType;
1212 return true;
1213 }
1214
Douglas Gregor033f56d2008-12-23 00:53:59 +00001215 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001216 // differences in the argument and result types are in Objective-C
1217 // pointer conversions. If so, we permit the conversion (but
1218 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001219 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001220 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001221 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001222 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001223 if (FromFunctionType && ToFunctionType) {
1224 // If the function types are exactly the same, this isn't an
1225 // Objective-C pointer conversion.
1226 if (Context.getCanonicalType(FromPointeeType)
1227 == Context.getCanonicalType(ToPointeeType))
1228 return false;
1229
1230 // Perform the quick checks that will tell us whether these
1231 // function types are obviously different.
1232 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1233 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1234 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1235 return false;
1236
1237 bool HasObjCConversion = false;
1238 if (Context.getCanonicalType(FromFunctionType->getResultType())
1239 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1240 // Okay, the types match exactly. Nothing to do.
1241 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1242 ToFunctionType->getResultType(),
1243 ConvertedType, IncompatibleObjC)) {
1244 // Okay, we have an Objective-C pointer conversion.
1245 HasObjCConversion = true;
1246 } else {
1247 // Function types are too different. Abort.
1248 return false;
1249 }
Mike Stump11289f42009-09-09 15:08:12 +00001250
Douglas Gregora119f102008-12-19 19:13:09 +00001251 // Check argument types.
1252 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1253 ArgIdx != NumArgs; ++ArgIdx) {
1254 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1255 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1256 if (Context.getCanonicalType(FromArgType)
1257 == Context.getCanonicalType(ToArgType)) {
1258 // Okay, the types match exactly. Nothing to do.
1259 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1260 ConvertedType, IncompatibleObjC)) {
1261 // Okay, we have an Objective-C pointer conversion.
1262 HasObjCConversion = true;
1263 } else {
1264 // Argument types are too different. Abort.
1265 return false;
1266 }
1267 }
1268
1269 if (HasObjCConversion) {
1270 // We had an Objective-C conversion. Allow this pointer
1271 // conversion, but complain about it.
1272 ConvertedType = ToType;
1273 IncompatibleObjC = true;
1274 return true;
1275 }
1276 }
1277
Sebastian Redl72b597d2009-01-25 19:43:20 +00001278 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001279}
1280
Douglas Gregor39c16d42008-10-24 04:54:22 +00001281/// CheckPointerConversion - Check the pointer conversion from the
1282/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001283/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001284/// conversions for which IsPointerConversion has already returned
1285/// true. It returns true and produces a diagnostic if there was an
1286/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001287bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001288 CastExpr::CastKind &Kind,
1289 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001290 QualType FromType = From->getType();
1291
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001292 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1293 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001294 QualType FromPointeeType = FromPtrType->getPointeeType(),
1295 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001296
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001297 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1298 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001299 // We must have a derived-to-base conversion. Check an
1300 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001301 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1302 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001303 From->getSourceRange(),
1304 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001305 return true;
1306
1307 // The conversion was successful.
1308 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001309 }
1310 }
Mike Stump11289f42009-09-09 15:08:12 +00001311 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001312 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001313 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001314 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001315 // Objective-C++ conversions are always okay.
1316 // FIXME: We should have a different class of conversions for the
1317 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001318 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001319 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001320
Steve Naroff7cae42b2009-07-10 23:34:53 +00001321 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001322 return false;
1323}
1324
Sebastian Redl72b597d2009-01-25 19:43:20 +00001325/// IsMemberPointerConversion - Determines whether the conversion of the
1326/// expression From, which has the (possibly adjusted) type FromType, can be
1327/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1328/// If so, returns true and places the converted type (that might differ from
1329/// ToType in its cv-qualifiers at some level) into ConvertedType.
1330bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001331 QualType ToType,
1332 bool InOverloadResolution,
1333 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001334 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001335 if (!ToTypePtr)
1336 return false;
1337
1338 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001339 if (From->isNullPointerConstant(Context,
1340 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1341 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001342 ConvertedType = ToType;
1343 return true;
1344 }
1345
1346 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001347 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001348 if (!FromTypePtr)
1349 return false;
1350
1351 // A pointer to member of B can be converted to a pointer to member of D,
1352 // where D is derived from B (C++ 4.11p2).
1353 QualType FromClass(FromTypePtr->getClass(), 0);
1354 QualType ToClass(ToTypePtr->getClass(), 0);
1355 // FIXME: What happens when these are dependent? Is this function even called?
1356
1357 if (IsDerivedFrom(ToClass, FromClass)) {
1358 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1359 ToClass.getTypePtr());
1360 return true;
1361 }
1362
1363 return false;
1364}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001365
Sebastian Redl72b597d2009-01-25 19:43:20 +00001366/// CheckMemberPointerConversion - Check the member pointer conversion from the
1367/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001368/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001369/// for which IsMemberPointerConversion has already returned true. It returns
1370/// true and produces a diagnostic if there was an error, or returns false
1371/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001372bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001373 CastExpr::CastKind &Kind,
1374 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001375 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001376 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001377 if (!FromPtrType) {
1378 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001379 assert(From->isNullPointerConstant(Context,
1380 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001381 "Expr must be null pointer constant!");
1382 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001383 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001384 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001385
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001386 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001387 assert(ToPtrType && "No member pointer cast has a target type "
1388 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001389
Sebastian Redled8f2002009-01-28 18:33:18 +00001390 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1391 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001392
Sebastian Redled8f2002009-01-28 18:33:18 +00001393 // FIXME: What about dependent types?
1394 assert(FromClass->isRecordType() && "Pointer into non-class.");
1395 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001396
John McCall5b0829a2010-02-10 09:31:12 +00001397 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001398 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001399 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1400 assert(DerivationOkay &&
1401 "Should not have been called if derivation isn't OK.");
1402 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001403
Sebastian Redled8f2002009-01-28 18:33:18 +00001404 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1405 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001406 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1407 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1408 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1409 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001410 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001411
Douglas Gregor89ee6822009-02-28 01:32:25 +00001412 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001413 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1414 << FromClass << ToClass << QualType(VBase, 0)
1415 << From->getSourceRange();
1416 return true;
1417 }
1418
John McCall5b0829a2010-02-10 09:31:12 +00001419 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001420 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1421 Paths.front(),
1422 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001423
Anders Carlssond7923c62009-08-22 23:33:40 +00001424 // Must be a base to derived member conversion.
1425 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001426 return false;
1427}
1428
Douglas Gregor9a657932008-10-21 23:43:52 +00001429/// IsQualificationConversion - Determines whether the conversion from
1430/// an rvalue of type FromType to ToType is a qualification conversion
1431/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001432bool
1433Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001434 FromType = Context.getCanonicalType(FromType);
1435 ToType = Context.getCanonicalType(ToType);
1436
1437 // If FromType and ToType are the same type, this is not a
1438 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001439 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001440 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001441
Douglas Gregor9a657932008-10-21 23:43:52 +00001442 // (C++ 4.4p4):
1443 // A conversion can add cv-qualifiers at levels other than the first
1444 // in multi-level pointers, subject to the following rules: [...]
1445 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001446 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001447 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001448 // Within each iteration of the loop, we check the qualifiers to
1449 // determine if this still looks like a qualification
1450 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001451 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001452 // until there are no more pointers or pointers-to-members left to
1453 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001454 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001455
1456 // -- for every j > 0, if const is in cv 1,j then const is in cv
1457 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001458 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001459 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Douglas Gregor9a657932008-10-21 23:43:52 +00001461 // -- if the cv 1,j and cv 2,j are different, then const is in
1462 // every cv for 0 < k < j.
1463 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001464 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001465 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001466
Douglas Gregor9a657932008-10-21 23:43:52 +00001467 // Keep track of whether all prior cv-qualifiers in the "to" type
1468 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001469 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001470 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001471 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001472
1473 // We are left with FromType and ToType being the pointee types
1474 // after unwrapping the original FromType and ToType the same number
1475 // of types. If we unwrapped any pointers, and if FromType and
1476 // ToType have the same unqualified type (since we checked
1477 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001478 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001479}
1480
Douglas Gregor576e98c2009-01-30 23:27:23 +00001481/// Determines whether there is a user-defined conversion sequence
1482/// (C++ [over.ics.user]) that converts expression From to the type
1483/// ToType. If such a conversion exists, User will contain the
1484/// user-defined conversion sequence that performs such a conversion
1485/// and this routine will return true. Otherwise, this routine returns
1486/// false and User is unspecified.
1487///
1488/// \param AllowConversionFunctions true if the conversion should
1489/// consider conversion functions at all. If false, only constructors
1490/// will be considered.
1491///
1492/// \param AllowExplicit true if the conversion should consider C++0x
1493/// "explicit" conversion functions as well as non-explicit conversion
1494/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001495///
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001496/// \param UserCast true if looking for user defined conversion for a static
1497/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001498OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1499 UserDefinedConversionSequence& User,
1500 OverloadCandidateSet& CandidateSet,
1501 bool AllowConversionFunctions,
1502 bool AllowExplicit,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001503 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001504 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001505 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1506 // We're not going to find any constructors.
1507 } else if (CXXRecordDecl *ToRecordDecl
1508 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001509 // C++ [over.match.ctor]p1:
1510 // When objects of class type are direct-initialized (8.5), or
1511 // copy-initialized from an expression of the same or a
1512 // derived class type (8.5), overload resolution selects the
1513 // constructor. [...] For copy-initialization, the candidate
1514 // functions are all the converting constructors (12.3.1) of
1515 // that class. The argument list is the expression-list within
1516 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001517 bool SuppressUserConversions = !UserCast;
1518 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1519 IsDerivedFrom(From->getType(), ToType)) {
1520 SuppressUserConversions = false;
1521 AllowConversionFunctions = false;
1522 }
1523
Mike Stump11289f42009-09-09 15:08:12 +00001524 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001525 = Context.DeclarationNames.getCXXConstructorName(
1526 Context.getCanonicalType(ToType).getUnqualifiedType());
1527 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001528 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001529 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001530 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001531 NamedDecl *D = *Con;
1532 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1533
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001534 // Find the constructor (which may be a template).
1535 CXXConstructorDecl *Constructor = 0;
1536 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001537 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001538 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001539 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001540 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1541 else
John McCalla0296f72010-03-19 07:35:19 +00001542 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001543
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001544 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001545 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001546 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001547 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001548 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001549 &From, 1, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00001550 SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001551 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001552 // Allow one user-defined conversion when user specifies a
1553 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001554 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001555 &From, 1, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00001556 SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001557 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001558 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001559 }
1560 }
1561
Douglas Gregor576e98c2009-01-30 23:27:23 +00001562 if (!AllowConversionFunctions) {
1563 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001564 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1565 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001566 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001567 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001568 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001569 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001570 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001571 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1572 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001573 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001574 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001575 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001576 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001577 DeclAccessPair FoundDecl = I.getPair();
1578 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001579 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1580 if (isa<UsingShadowDecl>(D))
1581 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1582
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001583 CXXConversionDecl *Conv;
1584 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001585 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1586 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001587 else
John McCallda4458e2010-03-31 01:36:47 +00001588 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001589
1590 if (AllowExplicit || !Conv->isExplicit()) {
1591 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001592 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001593 ActingContext, From, ToType,
1594 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001595 else
John McCalla0296f72010-03-19 07:35:19 +00001596 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001597 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001598 }
1599 }
1600 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001601 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001602
1603 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001604 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001605 case OR_Success:
1606 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001607 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001608 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1609 // C++ [over.ics.user]p1:
1610 // If the user-defined conversion is specified by a
1611 // constructor (12.3.1), the initial standard conversion
1612 // sequence converts the source type to the type required by
1613 // the argument of the constructor.
1614 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001615 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001616 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001617 User.EllipsisConversion = true;
1618 else {
1619 User.Before = Best->Conversions[0].Standard;
1620 User.EllipsisConversion = false;
1621 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001622 User.ConversionFunction = Constructor;
1623 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001624 User.After.setFromType(
1625 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001626 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001627 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001628 } else if (CXXConversionDecl *Conversion
1629 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1630 // C++ [over.ics.user]p1:
1631 //
1632 // [...] If the user-defined conversion is specified by a
1633 // conversion function (12.3.2), the initial standard
1634 // conversion sequence converts the source type to the
1635 // implicit object parameter of the conversion function.
1636 User.Before = Best->Conversions[0].Standard;
1637 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001638 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001639
1640 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001641 // The second standard conversion sequence converts the
1642 // result of the user-defined conversion to the target type
1643 // for the sequence. Since an implicit conversion sequence
1644 // is an initialization, the special rules for
1645 // initialization by user-defined conversion apply when
1646 // selecting the best user-defined conversion for a
1647 // user-defined conversion sequence (see 13.3.3 and
1648 // 13.3.3.1).
1649 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001650 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001651 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001652 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001653 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001654 }
Mike Stump11289f42009-09-09 15:08:12 +00001655
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001656 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001657 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001658 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001659 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001660 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001661
1662 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001663 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001664 }
1665
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001666 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001667}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001668
1669bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001670Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001671 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001672 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001673 OverloadingResult OvResult =
1674 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor7b23e412010-04-16 17:25:05 +00001675 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001676 if (OvResult == OR_Ambiguous)
1677 Diag(From->getSourceRange().getBegin(),
1678 diag::err_typecheck_ambiguous_condition)
1679 << From->getType() << ToType << From->getSourceRange();
1680 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1681 Diag(From->getSourceRange().getBegin(),
1682 diag::err_typecheck_nonviable_condition)
1683 << From->getType() << ToType << From->getSourceRange();
1684 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001685 return false;
John McCallad907772010-01-12 07:18:19 +00001686 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001687 return true;
1688}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001689
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001690/// CompareImplicitConversionSequences - Compare two implicit
1691/// conversion sequences to determine whether one is better than the
1692/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001693ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1695 const ImplicitConversionSequence& ICS2)
1696{
1697 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1698 // conversion sequences (as defined in 13.3.3.1)
1699 // -- a standard conversion sequence (13.3.3.1.1) is a better
1700 // conversion sequence than a user-defined conversion sequence or
1701 // an ellipsis conversion sequence, and
1702 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1703 // conversion sequence than an ellipsis conversion sequence
1704 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001705 //
John McCall0d1da222010-01-12 00:44:57 +00001706 // C++0x [over.best.ics]p10:
1707 // For the purpose of ranking implicit conversion sequences as
1708 // described in 13.3.3.2, the ambiguous conversion sequence is
1709 // treated as a user-defined sequence that is indistinguishable
1710 // from any other user-defined conversion sequence.
1711 if (ICS1.getKind() < ICS2.getKind()) {
1712 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1713 return ImplicitConversionSequence::Better;
1714 } else if (ICS2.getKind() < ICS1.getKind()) {
1715 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1716 return ImplicitConversionSequence::Worse;
1717 }
1718
1719 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1720 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001721
1722 // Two implicit conversion sequences of the same form are
1723 // indistinguishable conversion sequences unless one of the
1724 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001725 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001726 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001727 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001728 // User-defined conversion sequence U1 is a better conversion
1729 // sequence than another user-defined conversion sequence U2 if
1730 // they contain the same user-defined conversion function or
1731 // constructor and if the second standard conversion sequence of
1732 // U1 is better than the second standard conversion sequence of
1733 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001734 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001735 ICS2.UserDefined.ConversionFunction)
1736 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1737 ICS2.UserDefined.After);
1738 }
1739
1740 return ImplicitConversionSequence::Indistinguishable;
1741}
1742
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001743// Per 13.3.3.2p3, compare the given standard conversion sequences to
1744// determine if one is a proper subset of the other.
1745static ImplicitConversionSequence::CompareKind
1746compareStandardConversionSubsets(ASTContext &Context,
1747 const StandardConversionSequence& SCS1,
1748 const StandardConversionSequence& SCS2) {
1749 ImplicitConversionSequence::CompareKind Result
1750 = ImplicitConversionSequence::Indistinguishable;
1751
1752 if (SCS1.Second != SCS2.Second) {
1753 if (SCS1.Second == ICK_Identity)
1754 Result = ImplicitConversionSequence::Better;
1755 else if (SCS2.Second == ICK_Identity)
1756 Result = ImplicitConversionSequence::Worse;
1757 else
1758 return ImplicitConversionSequence::Indistinguishable;
1759 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1760 return ImplicitConversionSequence::Indistinguishable;
1761
1762 if (SCS1.Third == SCS2.Third) {
1763 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1764 : ImplicitConversionSequence::Indistinguishable;
1765 }
1766
1767 if (SCS1.Third == ICK_Identity)
1768 return Result == ImplicitConversionSequence::Worse
1769 ? ImplicitConversionSequence::Indistinguishable
1770 : ImplicitConversionSequence::Better;
1771
1772 if (SCS2.Third == ICK_Identity)
1773 return Result == ImplicitConversionSequence::Better
1774 ? ImplicitConversionSequence::Indistinguishable
1775 : ImplicitConversionSequence::Worse;
1776
1777 return ImplicitConversionSequence::Indistinguishable;
1778}
1779
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001780/// CompareStandardConversionSequences - Compare two standard
1781/// conversion sequences to determine whether one is better than the
1782/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001783ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001784Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1785 const StandardConversionSequence& SCS2)
1786{
1787 // Standard conversion sequence S1 is a better conversion sequence
1788 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1789
1790 // -- S1 is a proper subsequence of S2 (comparing the conversion
1791 // sequences in the canonical form defined by 13.3.3.1.1,
1792 // excluding any Lvalue Transformation; the identity conversion
1793 // sequence is considered to be a subsequence of any
1794 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001795 if (ImplicitConversionSequence::CompareKind CK
1796 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1797 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001798
1799 // -- the rank of S1 is better than the rank of S2 (by the rules
1800 // defined below), or, if not that,
1801 ImplicitConversionRank Rank1 = SCS1.getRank();
1802 ImplicitConversionRank Rank2 = SCS2.getRank();
1803 if (Rank1 < Rank2)
1804 return ImplicitConversionSequence::Better;
1805 else if (Rank2 < Rank1)
1806 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001807
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001808 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1809 // are indistinguishable unless one of the following rules
1810 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001811
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001812 // A conversion that is not a conversion of a pointer, or
1813 // pointer to member, to bool is better than another conversion
1814 // that is such a conversion.
1815 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1816 return SCS2.isPointerConversionToBool()
1817 ? ImplicitConversionSequence::Better
1818 : ImplicitConversionSequence::Worse;
1819
Douglas Gregor5c407d92008-10-23 00:40:37 +00001820 // C++ [over.ics.rank]p4b2:
1821 //
1822 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001823 // conversion of B* to A* is better than conversion of B* to
1824 // void*, and conversion of A* to void* is better than conversion
1825 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001826 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001827 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001828 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001829 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001830 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1831 // Exactly one of the conversion sequences is a conversion to
1832 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001833 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1834 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001835 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1836 // Neither conversion sequence converts to a void pointer; compare
1837 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001838 if (ImplicitConversionSequence::CompareKind DerivedCK
1839 = CompareDerivedToBaseConversions(SCS1, SCS2))
1840 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001841 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1842 // Both conversion sequences are conversions to void
1843 // pointers. Compare the source types to determine if there's an
1844 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001845 QualType FromType1 = SCS1.getFromType();
1846 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001847
1848 // Adjust the types we're converting from via the array-to-pointer
1849 // conversion, if we need to.
1850 if (SCS1.First == ICK_Array_To_Pointer)
1851 FromType1 = Context.getArrayDecayedType(FromType1);
1852 if (SCS2.First == ICK_Array_To_Pointer)
1853 FromType2 = Context.getArrayDecayedType(FromType2);
1854
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001855 QualType FromPointee1
1856 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1857 QualType FromPointee2
1858 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001859
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001860 if (IsDerivedFrom(FromPointee2, FromPointee1))
1861 return ImplicitConversionSequence::Better;
1862 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1863 return ImplicitConversionSequence::Worse;
1864
1865 // Objective-C++: If one interface is more specific than the
1866 // other, it is the better one.
1867 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1868 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1869 if (FromIface1 && FromIface1) {
1870 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1871 return ImplicitConversionSequence::Better;
1872 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1873 return ImplicitConversionSequence::Worse;
1874 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001875 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001876
1877 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1878 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001879 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001880 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001881 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001882
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001883 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001884 // C++0x [over.ics.rank]p3b4:
1885 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1886 // implicit object parameter of a non-static member function declared
1887 // without a ref-qualifier, and S1 binds an rvalue reference to an
1888 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001889 // FIXME: We don't know if we're dealing with the implicit object parameter,
1890 // or if the member function in this case has a ref qualifier.
1891 // (Of course, we don't have ref qualifiers yet.)
1892 if (SCS1.RRefBinding != SCS2.RRefBinding)
1893 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1894 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001895
1896 // C++ [over.ics.rank]p3b4:
1897 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1898 // which the references refer are the same type except for
1899 // top-level cv-qualifiers, and the type to which the reference
1900 // initialized by S2 refers is more cv-qualified than the type
1901 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001902 QualType T1 = SCS1.getToType(2);
1903 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001904 T1 = Context.getCanonicalType(T1);
1905 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001906 Qualifiers T1Quals, T2Quals;
1907 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1908 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1909 if (UnqualT1 == UnqualT2) {
1910 // 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);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001916 if (T2.isMoreQualifiedThan(T1))
1917 return ImplicitConversionSequence::Better;
1918 else if (T1.isMoreQualifiedThan(T2))
1919 return ImplicitConversionSequence::Worse;
1920 }
1921 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001922
1923 return ImplicitConversionSequence::Indistinguishable;
1924}
1925
1926/// CompareQualificationConversions - Compares two standard conversion
1927/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001928/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1929ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001930Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001931 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001932 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001933 // -- S1 and S2 differ only in their qualification conversion and
1934 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1935 // cv-qualification signature of type T1 is a proper subset of
1936 // the cv-qualification signature of type T2, and S1 is not the
1937 // deprecated string literal array-to-pointer conversion (4.2).
1938 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1939 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1940 return ImplicitConversionSequence::Indistinguishable;
1941
1942 // FIXME: the example in the standard doesn't use a qualification
1943 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001944 QualType T1 = SCS1.getToType(2);
1945 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001946 T1 = Context.getCanonicalType(T1);
1947 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001948 Qualifiers T1Quals, T2Quals;
1949 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1950 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001951
1952 // If the types are the same, we won't learn anything by unwrapped
1953 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001954 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001955 return ImplicitConversionSequence::Indistinguishable;
1956
Chandler Carruth607f38e2009-12-29 07:16:59 +00001957 // If the type is an array type, promote the element qualifiers to the type
1958 // for comparison.
1959 if (isa<ArrayType>(T1) && T1Quals)
1960 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1961 if (isa<ArrayType>(T2) && T2Quals)
1962 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1963
Mike Stump11289f42009-09-09 15:08:12 +00001964 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001965 = ImplicitConversionSequence::Indistinguishable;
1966 while (UnwrapSimilarPointerTypes(T1, T2)) {
1967 // Within each iteration of the loop, we check the qualifiers to
1968 // determine if this still looks like a qualification
1969 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001970 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001971 // until there are no more pointers or pointers-to-members left
1972 // to unwrap. This essentially mimics what
1973 // IsQualificationConversion does, but here we're checking for a
1974 // strict subset of qualifiers.
1975 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1976 // The qualifiers are the same, so this doesn't tell us anything
1977 // about how the sequences rank.
1978 ;
1979 else if (T2.isMoreQualifiedThan(T1)) {
1980 // T1 has fewer qualifiers, so it could be the better sequence.
1981 if (Result == ImplicitConversionSequence::Worse)
1982 // Neither has qualifiers that are a subset of the other's
1983 // qualifiers.
1984 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001985
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001986 Result = ImplicitConversionSequence::Better;
1987 } else if (T1.isMoreQualifiedThan(T2)) {
1988 // T2 has fewer qualifiers, so it could be the better sequence.
1989 if (Result == ImplicitConversionSequence::Better)
1990 // Neither has qualifiers that are a subset of the other's
1991 // qualifiers.
1992 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001993
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001994 Result = ImplicitConversionSequence::Worse;
1995 } else {
1996 // Qualifiers are disjoint.
1997 return ImplicitConversionSequence::Indistinguishable;
1998 }
1999
2000 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002001 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002002 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002003 }
2004
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002005 // Check that the winning standard conversion sequence isn't using
2006 // the deprecated string literal array to pointer conversion.
2007 switch (Result) {
2008 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002009 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002010 Result = ImplicitConversionSequence::Indistinguishable;
2011 break;
2012
2013 case ImplicitConversionSequence::Indistinguishable:
2014 break;
2015
2016 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002017 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002018 Result = ImplicitConversionSequence::Indistinguishable;
2019 break;
2020 }
2021
2022 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002023}
2024
Douglas Gregor5c407d92008-10-23 00:40:37 +00002025/// CompareDerivedToBaseConversions - Compares two standard conversion
2026/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002027/// various kinds of derived-to-base conversions (C++
2028/// [over.ics.rank]p4b3). As part of these checks, we also look at
2029/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002030ImplicitConversionSequence::CompareKind
2031Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2032 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002033 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002034 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002035 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002036 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002037
2038 // Adjust the types we're converting from via the array-to-pointer
2039 // conversion, if we need to.
2040 if (SCS1.First == ICK_Array_To_Pointer)
2041 FromType1 = Context.getArrayDecayedType(FromType1);
2042 if (SCS2.First == ICK_Array_To_Pointer)
2043 FromType2 = Context.getArrayDecayedType(FromType2);
2044
2045 // Canonicalize all of the types.
2046 FromType1 = Context.getCanonicalType(FromType1);
2047 ToType1 = Context.getCanonicalType(ToType1);
2048 FromType2 = Context.getCanonicalType(FromType2);
2049 ToType2 = Context.getCanonicalType(ToType2);
2050
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002051 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002052 //
2053 // If class B is derived directly or indirectly from class A and
2054 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002055 //
2056 // For Objective-C, we let A, B, and C also be Objective-C
2057 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002058
2059 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002060 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002061 SCS2.Second == ICK_Pointer_Conversion &&
2062 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2063 FromType1->isPointerType() && FromType2->isPointerType() &&
2064 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002065 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002066 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002067 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002068 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002069 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002070 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002071 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002072 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002073
John McCall9dd450b2009-09-21 23:43:11 +00002074 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2075 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2076 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2077 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002078
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002079 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002080 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2081 if (IsDerivedFrom(ToPointee1, ToPointee2))
2082 return ImplicitConversionSequence::Better;
2083 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2084 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002085
2086 if (ToIface1 && ToIface2) {
2087 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2088 return ImplicitConversionSequence::Better;
2089 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2090 return ImplicitConversionSequence::Worse;
2091 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002092 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002093
2094 // -- conversion of B* to A* is better than conversion of C* to A*,
2095 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2096 if (IsDerivedFrom(FromPointee2, FromPointee1))
2097 return ImplicitConversionSequence::Better;
2098 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2099 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002100
Douglas Gregor237f96c2008-11-26 23:31:11 +00002101 if (FromIface1 && FromIface2) {
2102 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2103 return ImplicitConversionSequence::Better;
2104 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2105 return ImplicitConversionSequence::Worse;
2106 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002107 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002108 }
2109
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002110 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002111 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2112 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2113 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2114 const MemberPointerType * FromMemPointer1 =
2115 FromType1->getAs<MemberPointerType>();
2116 const MemberPointerType * ToMemPointer1 =
2117 ToType1->getAs<MemberPointerType>();
2118 const MemberPointerType * FromMemPointer2 =
2119 FromType2->getAs<MemberPointerType>();
2120 const MemberPointerType * ToMemPointer2 =
2121 ToType2->getAs<MemberPointerType>();
2122 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2123 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2124 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2125 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2126 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2127 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2128 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2129 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002130 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002131 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2132 if (IsDerivedFrom(ToPointee1, ToPointee2))
2133 return ImplicitConversionSequence::Worse;
2134 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2135 return ImplicitConversionSequence::Better;
2136 }
2137 // conversion of B::* to C::* is better than conversion of A::* to C::*
2138 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2139 if (IsDerivedFrom(FromPointee1, FromPointee2))
2140 return ImplicitConversionSequence::Better;
2141 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2142 return ImplicitConversionSequence::Worse;
2143 }
2144 }
2145
Douglas Gregor83af86a2010-02-25 19:01:05 +00002146 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2147 (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
Douglas Gregor2fe98832008-11-03 19:09:14 +00002148 SCS1.Second == ICK_Derived_To_Base) {
2149 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002150 // -- binding of an expression of type C to a reference of type
2151 // B& is better than binding an expression of type C to a
2152 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002153 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2154 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002155 if (IsDerivedFrom(ToType1, ToType2))
2156 return ImplicitConversionSequence::Better;
2157 else if (IsDerivedFrom(ToType2, ToType1))
2158 return ImplicitConversionSequence::Worse;
2159 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002160
Douglas Gregor2fe98832008-11-03 19:09:14 +00002161 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002162 // -- binding of an expression of type B to a reference of type
2163 // A& is better than binding an expression of type C to a
2164 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002165 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2166 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002167 if (IsDerivedFrom(FromType2, FromType1))
2168 return ImplicitConversionSequence::Better;
2169 else if (IsDerivedFrom(FromType1, FromType2))
2170 return ImplicitConversionSequence::Worse;
2171 }
2172 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002173
Douglas Gregor5c407d92008-10-23 00:40:37 +00002174 return ImplicitConversionSequence::Indistinguishable;
2175}
2176
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002177/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2178/// determine whether they are reference-related,
2179/// reference-compatible, reference-compatible with added
2180/// qualification, or incompatible, for use in C++ initialization by
2181/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2182/// type, and the first type (T1) is the pointee type of the reference
2183/// type being initialized.
2184Sema::ReferenceCompareResult
2185Sema::CompareReferenceRelationship(SourceLocation Loc,
2186 QualType OrigT1, QualType OrigT2,
2187 bool& DerivedToBase) {
2188 assert(!OrigT1->isReferenceType() &&
2189 "T1 must be the pointee type of the reference type");
2190 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2191
2192 QualType T1 = Context.getCanonicalType(OrigT1);
2193 QualType T2 = Context.getCanonicalType(OrigT2);
2194 Qualifiers T1Quals, T2Quals;
2195 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2196 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2197
2198 // C++ [dcl.init.ref]p4:
2199 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2200 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2201 // T1 is a base class of T2.
2202 if (UnqualT1 == UnqualT2)
2203 DerivedToBase = false;
2204 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
2205 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
2206 IsDerivedFrom(UnqualT2, UnqualT1))
2207 DerivedToBase = true;
2208 else
2209 return Ref_Incompatible;
2210
2211 // At this point, we know that T1 and T2 are reference-related (at
2212 // least).
2213
2214 // If the type is an array type, promote the element qualifiers to the type
2215 // for comparison.
2216 if (isa<ArrayType>(T1) && T1Quals)
2217 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2218 if (isa<ArrayType>(T2) && T2Quals)
2219 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2220
2221 // C++ [dcl.init.ref]p4:
2222 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2223 // reference-related to T2 and cv1 is the same cv-qualification
2224 // as, or greater cv-qualification than, cv2. For purposes of
2225 // overload resolution, cases for which cv1 is greater
2226 // cv-qualification than cv2 are identified as
2227 // reference-compatible with added qualification (see 13.3.3.2).
2228 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2229 return Ref_Compatible;
2230 else if (T1.isMoreQualifiedThan(T2))
2231 return Ref_Compatible_With_Added_Qualification;
2232 else
2233 return Ref_Related;
2234}
2235
2236/// \brief Compute an implicit conversion sequence for reference
2237/// initialization.
2238static ImplicitConversionSequence
2239TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2240 SourceLocation DeclLoc,
2241 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002242 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002243 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2244
2245 // Most paths end in a failed conversion.
2246 ImplicitConversionSequence ICS;
2247 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2248
2249 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2250 QualType T2 = Init->getType();
2251
2252 // If the initializer is the address of an overloaded function, try
2253 // to resolve the overloaded function. If all goes well, T2 is the
2254 // type of the resulting function.
2255 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2256 DeclAccessPair Found;
2257 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2258 false, Found))
2259 T2 = Fn->getType();
2260 }
2261
2262 // Compute some basic properties of the types and the initializer.
2263 bool isRValRef = DeclType->isRValueReferenceType();
2264 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002265 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002266 Sema::ReferenceCompareResult RefRelationship
2267 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2268
2269 // C++ [dcl.init.ref]p5:
2270 // A reference to type "cv1 T1" is initialized by an expression
2271 // of type "cv2 T2" as follows:
2272
2273 // -- If the initializer expression
2274
2275 // C++ [over.ics.ref]p3:
2276 // Except for an implicit object parameter, for which see 13.3.1,
2277 // a standard conversion sequence cannot be formed if it requires
2278 // binding an lvalue reference to non-const to an rvalue or
2279 // binding an rvalue reference to an lvalue.
2280 if (isRValRef && InitLvalue == Expr::LV_Valid)
2281 return ICS;
2282
2283 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2284 // reference-compatible with "cv2 T2," or
2285 //
2286 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2287 if (InitLvalue == Expr::LV_Valid &&
2288 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2289 // C++ [over.ics.ref]p1:
2290 // When a parameter of reference type binds directly (8.5.3)
2291 // to an argument expression, the implicit conversion sequence
2292 // is the identity conversion, unless the argument expression
2293 // has a type that is a derived class of the parameter type,
2294 // in which case the implicit conversion sequence is a
2295 // derived-to-base Conversion (13.3.3.1).
2296 ICS.setStandard();
2297 ICS.Standard.First = ICK_Identity;
2298 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2299 ICS.Standard.Third = ICK_Identity;
2300 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2301 ICS.Standard.setToType(0, T2);
2302 ICS.Standard.setToType(1, T1);
2303 ICS.Standard.setToType(2, T1);
2304 ICS.Standard.ReferenceBinding = true;
2305 ICS.Standard.DirectBinding = true;
2306 ICS.Standard.RRefBinding = false;
2307 ICS.Standard.CopyConstructor = 0;
2308
2309 // Nothing more to do: the inaccessibility/ambiguity check for
2310 // derived-to-base conversions is suppressed when we're
2311 // computing the implicit conversion sequence (C++
2312 // [over.best.ics]p2).
2313 return ICS;
2314 }
2315
2316 // -- has a class type (i.e., T2 is a class type), where T1 is
2317 // not reference-related to T2, and can be implicitly
2318 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2319 // is reference-compatible with "cv3 T3" 92) (this
2320 // conversion is selected by enumerating the applicable
2321 // conversion functions (13.3.1.6) and choosing the best
2322 // one through overload resolution (13.3)),
2323 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2324 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2325 RefRelationship == Sema::Ref_Incompatible) {
2326 CXXRecordDecl *T2RecordDecl
2327 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2328
2329 OverloadCandidateSet CandidateSet(DeclLoc);
2330 const UnresolvedSetImpl *Conversions
2331 = T2RecordDecl->getVisibleConversionFunctions();
2332 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2333 E = Conversions->end(); I != E; ++I) {
2334 NamedDecl *D = *I;
2335 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2336 if (isa<UsingShadowDecl>(D))
2337 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2338
2339 FunctionTemplateDecl *ConvTemplate
2340 = dyn_cast<FunctionTemplateDecl>(D);
2341 CXXConversionDecl *Conv;
2342 if (ConvTemplate)
2343 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2344 else
2345 Conv = cast<CXXConversionDecl>(D);
2346
2347 // If the conversion function doesn't return a reference type,
2348 // it can't be considered for this conversion.
2349 if (Conv->getConversionType()->isLValueReferenceType() &&
2350 (AllowExplicit || !Conv->isExplicit())) {
2351 if (ConvTemplate)
2352 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2353 Init, DeclType, CandidateSet);
2354 else
2355 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2356 DeclType, CandidateSet);
2357 }
2358 }
2359
2360 OverloadCandidateSet::iterator Best;
2361 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2362 case OR_Success:
2363 // C++ [over.ics.ref]p1:
2364 //
2365 // [...] If the parameter binds directly to the result of
2366 // applying a conversion function to the argument
2367 // expression, the implicit conversion sequence is a
2368 // user-defined conversion sequence (13.3.3.1.2), with the
2369 // second standard conversion sequence either an identity
2370 // conversion or, if the conversion function returns an
2371 // entity of a type that is a derived class of the parameter
2372 // type, a derived-to-base Conversion.
2373 if (!Best->FinalConversion.DirectBinding)
2374 break;
2375
2376 ICS.setUserDefined();
2377 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2378 ICS.UserDefined.After = Best->FinalConversion;
2379 ICS.UserDefined.ConversionFunction = Best->Function;
2380 ICS.UserDefined.EllipsisConversion = false;
2381 assert(ICS.UserDefined.After.ReferenceBinding &&
2382 ICS.UserDefined.After.DirectBinding &&
2383 "Expected a direct reference binding!");
2384 return ICS;
2385
2386 case OR_Ambiguous:
2387 ICS.setAmbiguous();
2388 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2389 Cand != CandidateSet.end(); ++Cand)
2390 if (Cand->Viable)
2391 ICS.Ambiguous.addConversion(Cand->Function);
2392 return ICS;
2393
2394 case OR_No_Viable_Function:
2395 case OR_Deleted:
2396 // There was no suitable conversion, or we found a deleted
2397 // conversion; continue with other checks.
2398 break;
2399 }
2400 }
2401
2402 // -- Otherwise, the reference shall be to a non-volatile const
2403 // type (i.e., cv1 shall be const), or the reference shall be an
2404 // rvalue reference and the initializer expression shall be an rvalue.
2405 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const)
2406 return ICS;
2407
2408 // -- If the initializer expression is an rvalue, with T2 a
2409 // class type, and "cv1 T1" is reference-compatible with
2410 // "cv2 T2," the reference is bound in one of the
2411 // following ways (the choice is implementation-defined):
2412 //
2413 // -- The reference is bound to the object represented by
2414 // the rvalue (see 3.10) or to a sub-object within that
2415 // object.
2416 //
2417 // -- A temporary of type "cv1 T2" [sic] is created, and
2418 // a constructor is called to copy the entire rvalue
2419 // object into the temporary. The reference is bound to
2420 // the temporary or to a sub-object within the
2421 // temporary.
2422 //
2423 // The constructor that would be used to make the copy
2424 // shall be callable whether or not the copy is actually
2425 // done.
2426 //
2427 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
2428 // freedom, so we will always take the first option and never build
2429 // a temporary in this case.
2430 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2431 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2432 ICS.setStandard();
2433 ICS.Standard.First = ICK_Identity;
2434 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2435 ICS.Standard.Third = ICK_Identity;
2436 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2437 ICS.Standard.setToType(0, T2);
2438 ICS.Standard.setToType(1, T1);
2439 ICS.Standard.setToType(2, T1);
2440 ICS.Standard.ReferenceBinding = true;
2441 ICS.Standard.DirectBinding = false;
2442 ICS.Standard.RRefBinding = isRValRef;
2443 ICS.Standard.CopyConstructor = 0;
2444 return ICS;
2445 }
2446
2447 // -- Otherwise, a temporary of type "cv1 T1" is created and
2448 // initialized from the initializer expression using the
2449 // rules for a non-reference copy initialization (8.5). The
2450 // reference is then bound to the temporary. If T1 is
2451 // reference-related to T2, cv1 must be the same
2452 // cv-qualification as, or greater cv-qualification than,
2453 // cv2; otherwise, the program is ill-formed.
2454 if (RefRelationship == Sema::Ref_Related) {
2455 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2456 // we would be reference-compatible or reference-compatible with
2457 // added qualification. But that wasn't the case, so the reference
2458 // initialization fails.
2459 return ICS;
2460 }
2461
2462 // If at least one of the types is a class type, the types are not
2463 // related, and we aren't allowed any user conversions, the
2464 // reference binding fails. This case is important for breaking
2465 // recursion, since TryImplicitConversion below will attempt to
2466 // create a temporary through the use of a copy constructor.
2467 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2468 (T1->isRecordType() || T2->isRecordType()))
2469 return ICS;
2470
2471 // C++ [over.ics.ref]p2:
2472 //
2473 // When a parameter of reference type is not bound directly to
2474 // an argument expression, the conversion sequence is the one
2475 // required to convert the argument expression to the
2476 // underlying type of the reference according to
2477 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2478 // to copy-initializing a temporary of the underlying type with
2479 // the argument expression. Any difference in top-level
2480 // cv-qualification is subsumed by the initialization itself
2481 // and does not constitute a conversion.
2482 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2483 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002484 /*InOverloadResolution=*/false);
2485
2486 // Of course, that's still a reference binding.
2487 if (ICS.isStandard()) {
2488 ICS.Standard.ReferenceBinding = true;
2489 ICS.Standard.RRefBinding = isRValRef;
2490 } else if (ICS.isUserDefined()) {
2491 ICS.UserDefined.After.ReferenceBinding = true;
2492 ICS.UserDefined.After.RRefBinding = isRValRef;
2493 }
2494 return ICS;
2495}
2496
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002497/// TryCopyInitialization - Try to copy-initialize a value of type
2498/// ToType from the expression From. Return the implicit conversion
2499/// sequence required to pass this argument, which may be a bad
2500/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002501/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002502/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002503static ImplicitConversionSequence
2504TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002505 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002506 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002507 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002508 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002509 /*FIXME:*/From->getLocStart(),
2510 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002511 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002512
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002513 return S.TryImplicitConversion(From, ToType,
2514 SuppressUserConversions,
2515 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002516 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002517}
2518
Douglas Gregor436424c2008-11-18 23:14:02 +00002519/// TryObjectArgumentInitialization - Try to initialize the object
2520/// parameter of the given member function (@c Method) from the
2521/// expression @p From.
2522ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002523Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002524 CXXMethodDecl *Method,
2525 CXXRecordDecl *ActingContext) {
2526 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002527 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2528 // const volatile object.
2529 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2530 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2531 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002532
2533 // Set up the conversion sequence as a "bad" conversion, to allow us
2534 // to exit early.
2535 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002536
2537 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002538 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002539 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002540 FromType = PT->getPointeeType();
2541
2542 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002543
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002544 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002545 // where X is the class of which the function is a member
2546 // (C++ [over.match.funcs]p4). However, when finding an implicit
2547 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002548 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002549 // (C++ [over.match.funcs]p5). We perform a simplified version of
2550 // reference binding here, that allows class rvalues to bind to
2551 // non-constant references.
2552
2553 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2554 // with the implicit object parameter (C++ [over.match.funcs]p5).
2555 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002556 if (ImplicitParamType.getCVRQualifiers()
2557 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002558 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002559 ICS.setBad(BadConversionSequence::bad_qualifiers,
2560 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002561 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002562 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002563
2564 // Check that we have either the same type or a derived type. It
2565 // affects the conversion rank.
2566 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002567 ImplicitConversionKind SecondKind;
2568 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2569 SecondKind = ICK_Identity;
2570 } else if (IsDerivedFrom(FromType, ClassType))
2571 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002572 else {
John McCall65eb8792010-02-25 01:37:24 +00002573 ICS.setBad(BadConversionSequence::unrelated_class,
2574 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002575 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002576 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002577
2578 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002579 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002580 ICS.Standard.setAsIdentityConversion();
2581 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002582 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002583 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002584 ICS.Standard.ReferenceBinding = true;
2585 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002586 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002587 return ICS;
2588}
2589
2590/// PerformObjectArgumentInitialization - Perform initialization of
2591/// the implicit object parameter for the given Method with the given
2592/// expression.
2593bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002594Sema::PerformObjectArgumentInitialization(Expr *&From,
2595 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002596 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002597 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002598 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002599 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002600 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002601
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002602 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002603 FromRecordType = PT->getPointeeType();
2604 DestType = Method->getThisType(Context);
2605 } else {
2606 FromRecordType = From->getType();
2607 DestType = ImplicitParamRecordType;
2608 }
2609
John McCall6e9f8f62009-12-03 04:06:58 +00002610 // Note that we always use the true parent context when performing
2611 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002612 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002613 = TryObjectArgumentInitialization(From->getType(), Method,
2614 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002615 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002616 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002617 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002618 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002619
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002620 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002621 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002622
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002623 if (!Context.hasSameType(From->getType(), DestType))
2624 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2625 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002626 return false;
2627}
2628
Douglas Gregor5fb53972009-01-14 15:45:31 +00002629/// TryContextuallyConvertToBool - Attempt to contextually convert the
2630/// expression From to bool (C++0x [conv]p3).
2631ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002632 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002633 // FIXME: Are these flags correct?
2634 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002635 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002636 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002637}
2638
2639/// PerformContextuallyConvertToBool - Perform a contextual conversion
2640/// of the expression From to bool (C++0x [conv]p3).
2641bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2642 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002643 if (!ICS.isBad())
2644 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002645
Fariborz Jahanian76197412009-11-18 18:26:29 +00002646 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002647 return Diag(From->getSourceRange().getBegin(),
2648 diag::err_typecheck_bool_condition)
2649 << From->getType() << From->getSourceRange();
2650 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002651}
2652
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002653/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002654/// candidate functions, using the given function call arguments. If
2655/// @p SuppressUserConversions, then don't allow user-defined
2656/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002657///
2658/// \para PartialOverloading true if we are performing "partial" overloading
2659/// based on an incomplete set of function arguments. This feature is used by
2660/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002661void
2662Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002663 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002664 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002665 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002666 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002667 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002668 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002669 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002670 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002671 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002672 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002673
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002674 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002675 if (!isa<CXXConstructorDecl>(Method)) {
2676 // If we get here, it's because we're calling a member function
2677 // that is named without a member access expression (e.g.,
2678 // "this->f") that was either written explicitly or created
2679 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002680 // function, e.g., X::f(). We use an empty type for the implied
2681 // object argument (C++ [over.call.func]p3), and the acting context
2682 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002683 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002684 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002685 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002686 return;
2687 }
2688 // We treat a constructor like a non-member function, since its object
2689 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002690 }
2691
Douglas Gregorff7028a2009-11-13 23:59:09 +00002692 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002693 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002694
Douglas Gregor27381f32009-11-23 12:27:39 +00002695 // Overload resolution is always an unevaluated context.
2696 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2697
Douglas Gregorffe14e32009-11-14 01:20:54 +00002698 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2699 // C++ [class.copy]p3:
2700 // A member function template is never instantiated to perform the copy
2701 // of a class object to an object of its class type.
2702 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2703 if (NumArgs == 1 &&
2704 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002705 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2706 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002707 return;
2708 }
2709
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002710 // Add this candidate
2711 CandidateSet.push_back(OverloadCandidate());
2712 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002713 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002714 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002715 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002716 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002717 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002718
2719 unsigned NumArgsInProto = Proto->getNumArgs();
2720
2721 // (C++ 13.3.2p2): A candidate function having fewer than m
2722 // parameters is viable only if it has an ellipsis in its parameter
2723 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002724 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2725 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002726 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002727 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002728 return;
2729 }
2730
2731 // (C++ 13.3.2p2): A candidate function having more than m parameters
2732 // is viable only if the (m+1)st parameter has a default argument
2733 // (8.3.6). For the purposes of overload resolution, the
2734 // parameter list is truncated on the right, so that there are
2735 // exactly m parameters.
2736 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002737 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002738 // Not enough arguments.
2739 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002740 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002741 return;
2742 }
2743
2744 // Determine the implicit conversion sequences for each of the
2745 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002746 Candidate.Conversions.resize(NumArgs);
2747 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2748 if (ArgIdx < NumArgsInProto) {
2749 // (C++ 13.3.2p3): for F to be a viable function, there shall
2750 // exist for each argument an implicit conversion sequence
2751 // (13.3.3.1) that converts that argument to the corresponding
2752 // parameter of F.
2753 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002754 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002755 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002756 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00002757 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002758 if (Candidate.Conversions[ArgIdx].isBad()) {
2759 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002760 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002761 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002762 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002763 } else {
2764 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2765 // argument for which there is no corresponding parameter is
2766 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002767 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002768 }
2769 }
2770}
2771
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002772/// \brief Add all of the function declarations in the given function set to
2773/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002774void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002775 Expr **Args, unsigned NumArgs,
2776 OverloadCandidateSet& CandidateSet,
2777 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002778 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00002779 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2780 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002781 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002782 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002783 cast<CXXMethodDecl>(FD)->getParent(),
2784 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002785 CandidateSet, SuppressUserConversions);
2786 else
John McCalla0296f72010-03-19 07:35:19 +00002787 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002788 SuppressUserConversions);
2789 } else {
John McCalla0296f72010-03-19 07:35:19 +00002790 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002791 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2792 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002793 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002794 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002795 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002796 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002797 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002798 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002799 else
John McCalla0296f72010-03-19 07:35:19 +00002800 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00002801 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002802 Args, NumArgs, CandidateSet,
2803 SuppressUserConversions);
2804 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002805 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002806}
2807
John McCallf0f1cf02009-11-17 07:50:12 +00002808/// AddMethodCandidate - Adds a named decl (which is some kind of
2809/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00002810void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002811 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002812 Expr **Args, unsigned NumArgs,
2813 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002814 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00002815 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002816 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002817
2818 if (isa<UsingShadowDecl>(Decl))
2819 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2820
2821 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2822 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2823 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00002824 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2825 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002826 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002827 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002828 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002829 } else {
John McCalla0296f72010-03-19 07:35:19 +00002830 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002831 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002832 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002833 }
2834}
2835
Douglas Gregor436424c2008-11-18 23:14:02 +00002836/// AddMethodCandidate - Adds the given C++ member function to the set
2837/// of candidate functions, using the given function call arguments
2838/// and the object argument (@c Object). For example, in a call
2839/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2840/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2841/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00002842/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00002843void
John McCalla0296f72010-03-19 07:35:19 +00002844Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002845 CXXRecordDecl *ActingContext, QualType ObjectType,
2846 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002847 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002848 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002849 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002850 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002851 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002852 assert(!isa<CXXConstructorDecl>(Method) &&
2853 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002854
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002855 if (!CandidateSet.isNewCandidate(Method))
2856 return;
2857
Douglas Gregor27381f32009-11-23 12:27:39 +00002858 // Overload resolution is always an unevaluated context.
2859 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2860
Douglas Gregor436424c2008-11-18 23:14:02 +00002861 // Add this candidate
2862 CandidateSet.push_back(OverloadCandidate());
2863 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002864 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00002865 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002866 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002867 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002868
2869 unsigned NumArgsInProto = Proto->getNumArgs();
2870
2871 // (C++ 13.3.2p2): A candidate function having fewer than m
2872 // parameters is viable only if it has an ellipsis in its parameter
2873 // list (8.3.5).
2874 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2875 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002876 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002877 return;
2878 }
2879
2880 // (C++ 13.3.2p2): A candidate function having more than m parameters
2881 // is viable only if the (m+1)st parameter has a default argument
2882 // (8.3.6). For the purposes of overload resolution, the
2883 // parameter list is truncated on the right, so that there are
2884 // exactly m parameters.
2885 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2886 if (NumArgs < MinRequiredArgs) {
2887 // Not enough arguments.
2888 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002889 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002890 return;
2891 }
2892
2893 Candidate.Viable = true;
2894 Candidate.Conversions.resize(NumArgs + 1);
2895
John McCall6e9f8f62009-12-03 04:06:58 +00002896 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002897 // The implicit object argument is ignored.
2898 Candidate.IgnoreObjectArgument = true;
2899 else {
2900 // Determine the implicit conversion sequence for the object
2901 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002902 Candidate.Conversions[0]
2903 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002904 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002905 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002906 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002907 return;
2908 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002909 }
2910
2911 // Determine the implicit conversion sequences for each of the
2912 // arguments.
2913 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2914 if (ArgIdx < NumArgsInProto) {
2915 // (C++ 13.3.2p3): for F to be a viable function, there shall
2916 // exist for each argument an implicit conversion sequence
2917 // (13.3.3.1) that converts that argument to the corresponding
2918 // parameter of F.
2919 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002920 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002921 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002922 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00002923 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002924 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002925 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002926 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002927 break;
2928 }
2929 } else {
2930 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2931 // argument for which there is no corresponding parameter is
2932 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002933 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002934 }
2935 }
2936}
2937
Douglas Gregor97628d62009-08-21 00:16:32 +00002938/// \brief Add a C++ member function template as a candidate to the candidate
2939/// set, using template argument deduction to produce an appropriate member
2940/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002941void
Douglas Gregor97628d62009-08-21 00:16:32 +00002942Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00002943 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002944 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002945 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002946 QualType ObjectType,
2947 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002948 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002949 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002950 if (!CandidateSet.isNewCandidate(MethodTmpl))
2951 return;
2952
Douglas Gregor97628d62009-08-21 00:16:32 +00002953 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002954 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002955 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002956 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002957 // candidate functions in the usual way.113) A given name can refer to one
2958 // or more function templates and also to a set of overloaded non-template
2959 // functions. In such a case, the candidate functions generated from each
2960 // function template are combined with the set of non-template candidate
2961 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002962 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00002963 FunctionDecl *Specialization = 0;
2964 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002965 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002966 Args, NumArgs, Specialization, Info)) {
2967 // FIXME: Record what happened with template argument deduction, so
2968 // that we can give the user a beautiful diagnostic.
2969 (void)Result;
2970 return;
2971 }
Mike Stump11289f42009-09-09 15:08:12 +00002972
Douglas Gregor97628d62009-08-21 00:16:32 +00002973 // Add the function template specialization produced by template argument
2974 // deduction as a candidate.
2975 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002976 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002977 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00002978 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002979 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002980 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00002981}
2982
Douglas Gregor05155d82009-08-21 23:19:43 +00002983/// \brief Add a C++ function template specialization as a candidate
2984/// in the candidate set, using template argument deduction to produce
2985/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002986void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002987Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00002988 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00002989 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002990 Expr **Args, unsigned NumArgs,
2991 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002992 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002993 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2994 return;
2995
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002996 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002997 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002998 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002999 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003000 // candidate functions in the usual way.113) A given name can refer to one
3001 // or more function templates and also to a set of overloaded non-template
3002 // functions. In such a case, the candidate functions generated from each
3003 // function template are combined with the set of non-template candidate
3004 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003005 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003006 FunctionDecl *Specialization = 0;
3007 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003008 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003009 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003010 CandidateSet.push_back(OverloadCandidate());
3011 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003012 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003013 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3014 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003015 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003016 Candidate.IsSurrogate = false;
3017 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00003018
3019 // TODO: record more information about failed template arguments
3020 Candidate.DeductionFailure.Result = Result;
3021 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003022 return;
3023 }
Mike Stump11289f42009-09-09 15:08:12 +00003024
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003025 // Add the function template specialization produced by template argument
3026 // deduction as a candidate.
3027 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003028 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003029 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003030}
Mike Stump11289f42009-09-09 15:08:12 +00003031
Douglas Gregora1f013e2008-11-07 22:36:19 +00003032/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003033/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003034/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003035/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003036/// (which may or may not be the same type as the type that the
3037/// conversion function produces).
3038void
3039Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003040 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003041 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003042 Expr *From, QualType ToType,
3043 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003044 assert(!Conversion->getDescribedFunctionTemplate() &&
3045 "Conversion function templates use AddTemplateConversionCandidate");
3046
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003047 if (!CandidateSet.isNewCandidate(Conversion))
3048 return;
3049
Douglas Gregor27381f32009-11-23 12:27:39 +00003050 // Overload resolution is always an unevaluated context.
3051 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3052
Douglas Gregora1f013e2008-11-07 22:36:19 +00003053 // Add this candidate
3054 CandidateSet.push_back(OverloadCandidate());
3055 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003056 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003057 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003058 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003059 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003060 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00003061 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003062 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003063
Douglas Gregor436424c2008-11-18 23:14:02 +00003064 // Determine the implicit conversion sequence for the implicit
3065 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003066 Candidate.Viable = true;
3067 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003068 Candidate.Conversions[0]
3069 = TryObjectArgumentInitialization(From->getType(), Conversion,
3070 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003071 // Conversion functions to a different type in the base class is visible in
3072 // the derived class. So, a derived to base conversion should not participate
3073 // in overload resolution.
3074 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3075 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003076 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003077 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003078 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003079 return;
3080 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003081
3082 // We won't go through a user-define type conversion function to convert a
3083 // derived to base as such conversions are given Conversion Rank. They only
3084 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3085 QualType FromCanon
3086 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3087 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3088 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3089 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003090 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003091 return;
3092 }
3093
Douglas Gregora1f013e2008-11-07 22:36:19 +00003094
3095 // To determine what the conversion from the result of calling the
3096 // conversion function to the type we're eventually trying to
3097 // convert to (ToType), we need to synthesize a call to the
3098 // conversion function and attempt copy initialization from it. This
3099 // makes sure that we get the right semantics with respect to
3100 // lvalues/rvalues and the type. Fortunately, we can allocate this
3101 // call on the stack and we don't need its arguments to be
3102 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003103 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003104 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003105 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003106 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00003107 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00003108
3109 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003110 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3111 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003112 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003113 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003114 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003115 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003116 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003117 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003118 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003119
John McCall0d1da222010-01-12 00:44:57 +00003120 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003121 case ImplicitConversionSequence::StandardConversion:
3122 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003123
3124 // C++ [over.ics.user]p3:
3125 // If the user-defined conversion is specified by a specialization of a
3126 // conversion function template, the second standard conversion sequence
3127 // shall have exact match rank.
3128 if (Conversion->getPrimaryTemplate() &&
3129 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3130 Candidate.Viable = false;
3131 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3132 }
3133
Douglas Gregora1f013e2008-11-07 22:36:19 +00003134 break;
3135
3136 case ImplicitConversionSequence::BadConversion:
3137 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003138 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003139 break;
3140
3141 default:
Mike Stump11289f42009-09-09 15:08:12 +00003142 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003143 "Can only end up with a standard conversion sequence or failure");
3144 }
3145}
3146
Douglas Gregor05155d82009-08-21 23:19:43 +00003147/// \brief Adds a conversion function template specialization
3148/// candidate to the overload set, using template argument deduction
3149/// to deduce the template arguments of the conversion function
3150/// template from the type that we are converting to (C++
3151/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003152void
Douglas Gregor05155d82009-08-21 23:19:43 +00003153Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003154 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003155 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003156 Expr *From, QualType ToType,
3157 OverloadCandidateSet &CandidateSet) {
3158 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3159 "Only conversion function templates permitted here");
3160
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003161 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3162 return;
3163
John McCallbc077cf2010-02-08 23:07:23 +00003164 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003165 CXXConversionDecl *Specialization = 0;
3166 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003167 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003168 Specialization, Info)) {
3169 // FIXME: Record what happened with template argument deduction, so
3170 // that we can give the user a beautiful diagnostic.
3171 (void)Result;
3172 return;
3173 }
Mike Stump11289f42009-09-09 15:08:12 +00003174
Douglas Gregor05155d82009-08-21 23:19:43 +00003175 // Add the conversion function template specialization produced by
3176 // template argument deduction as a candidate.
3177 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003178 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003179 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003180}
3181
Douglas Gregorab7897a2008-11-19 22:57:39 +00003182/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3183/// converts the given @c Object to a function pointer via the
3184/// conversion function @c Conversion, and then attempts to call it
3185/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3186/// the type of function that we'll eventually be calling.
3187void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003188 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003189 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003190 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003191 QualType ObjectType,
3192 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003193 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003194 if (!CandidateSet.isNewCandidate(Conversion))
3195 return;
3196
Douglas Gregor27381f32009-11-23 12:27:39 +00003197 // Overload resolution is always an unevaluated context.
3198 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3199
Douglas Gregorab7897a2008-11-19 22:57:39 +00003200 CandidateSet.push_back(OverloadCandidate());
3201 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003202 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003203 Candidate.Function = 0;
3204 Candidate.Surrogate = Conversion;
3205 Candidate.Viable = true;
3206 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003207 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003208 Candidate.Conversions.resize(NumArgs + 1);
3209
3210 // Determine the implicit conversion sequence for the implicit
3211 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003212 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003213 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003214 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003215 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003216 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003217 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003218 return;
3219 }
3220
3221 // The first conversion is actually a user-defined conversion whose
3222 // first conversion is ObjectInit's standard conversion (which is
3223 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003224 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003225 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003226 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003227 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003228 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003229 = Candidate.Conversions[0].UserDefined.Before;
3230 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3231
Mike Stump11289f42009-09-09 15:08:12 +00003232 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003233 unsigned NumArgsInProto = Proto->getNumArgs();
3234
3235 // (C++ 13.3.2p2): A candidate function having fewer than m
3236 // parameters is viable only if it has an ellipsis in its parameter
3237 // list (8.3.5).
3238 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3239 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003240 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003241 return;
3242 }
3243
3244 // Function types don't have any default arguments, so just check if
3245 // we have enough arguments.
3246 if (NumArgs < NumArgsInProto) {
3247 // Not enough arguments.
3248 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003249 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003250 return;
3251 }
3252
3253 // Determine the implicit conversion sequences for each of the
3254 // arguments.
3255 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3256 if (ArgIdx < NumArgsInProto) {
3257 // (C++ 13.3.2p3): for F to be a viable function, there shall
3258 // exist for each argument an implicit conversion sequence
3259 // (13.3.3.1) that converts that argument to the corresponding
3260 // parameter of F.
3261 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003262 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003263 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003264 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003265 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003266 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003267 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003268 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003269 break;
3270 }
3271 } else {
3272 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3273 // argument for which there is no corresponding parameter is
3274 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003275 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003276 }
3277 }
3278}
3279
Mike Stump87c57ac2009-05-16 07:39:55 +00003280// FIXME: This will eventually be removed, once we've migrated all of the
3281// operator overloading logic over to the scheme used by binary operators, which
3282// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003283void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003284 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003285 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003286 OverloadCandidateSet& CandidateSet,
3287 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003288 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003289
3290 QualType T1 = Args[0]->getType();
3291 QualType T2;
3292 if (NumArgs > 1)
3293 T2 = Args[1]->getType();
3294
3295 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003296 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003297 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3298 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3299 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3300 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003301 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003302 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003303}
3304
3305/// \brief Add overload candidates for overloaded operators that are
3306/// member functions.
3307///
3308/// Add the overloaded operator candidates that are member functions
3309/// for the operator Op that was used in an operator expression such
3310/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3311/// CandidateSet will store the added overload candidates. (C++
3312/// [over.match.oper]).
3313void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3314 SourceLocation OpLoc,
3315 Expr **Args, unsigned NumArgs,
3316 OverloadCandidateSet& CandidateSet,
3317 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003318 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3319
3320 // C++ [over.match.oper]p3:
3321 // For a unary operator @ with an operand of a type whose
3322 // cv-unqualified version is T1, and for a binary operator @ with
3323 // a left operand of a type whose cv-unqualified version is T1 and
3324 // a right operand of a type whose cv-unqualified version is T2,
3325 // three sets of candidate functions, designated member
3326 // candidates, non-member candidates and built-in candidates, are
3327 // constructed as follows:
3328 QualType T1 = Args[0]->getType();
3329 QualType T2;
3330 if (NumArgs > 1)
3331 T2 = Args[1]->getType();
3332
3333 // -- If T1 is a class type, the set of member candidates is the
3334 // result of the qualified lookup of T1::operator@
3335 // (13.3.1.1.1); otherwise, the set of member candidates is
3336 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003337 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003338 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003339 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003340 return;
Mike Stump11289f42009-09-09 15:08:12 +00003341
John McCall27b18f82009-11-17 02:14:36 +00003342 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3343 LookupQualifiedName(Operators, T1Rec->getDecl());
3344 Operators.suppressDiagnostics();
3345
Mike Stump11289f42009-09-09 15:08:12 +00003346 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003347 OperEnd = Operators.end();
3348 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003349 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003350 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003351 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003352 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003353 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003354}
3355
Douglas Gregora11693b2008-11-12 17:17:38 +00003356/// AddBuiltinCandidate - Add a candidate for a built-in
3357/// operator. ResultTy and ParamTys are the result and parameter types
3358/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003359/// arguments being passed to the candidate. IsAssignmentOperator
3360/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003361/// operator. NumContextualBoolArguments is the number of arguments
3362/// (at the beginning of the argument list) that will be contextually
3363/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003364void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003365 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003366 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003367 bool IsAssignmentOperator,
3368 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003369 // Overload resolution is always an unevaluated context.
3370 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3371
Douglas Gregora11693b2008-11-12 17:17:38 +00003372 // Add this candidate
3373 CandidateSet.push_back(OverloadCandidate());
3374 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003375 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003376 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003377 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003378 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003379 Candidate.BuiltinTypes.ResultTy = ResultTy;
3380 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3381 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3382
3383 // Determine the implicit conversion sequences for each of the
3384 // arguments.
3385 Candidate.Viable = true;
3386 Candidate.Conversions.resize(NumArgs);
3387 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003388 // C++ [over.match.oper]p4:
3389 // For the built-in assignment operators, conversions of the
3390 // left operand are restricted as follows:
3391 // -- no temporaries are introduced to hold the left operand, and
3392 // -- no user-defined conversions are applied to the left
3393 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003394 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003395 //
3396 // We block these conversions by turning off user-defined
3397 // conversions, since that is the only way that initialization of
3398 // a reference to a non-class type can occur from something that
3399 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003400 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003401 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003402 "Contextual conversion to bool requires bool type");
3403 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3404 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003405 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003406 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003407 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003408 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003409 }
John McCall0d1da222010-01-12 00:44:57 +00003410 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003411 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003412 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003413 break;
3414 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003415 }
3416}
3417
3418/// BuiltinCandidateTypeSet - A set of types that will be used for the
3419/// candidate operator functions for built-in operators (C++
3420/// [over.built]). The types are separated into pointer types and
3421/// enumeration types.
3422class BuiltinCandidateTypeSet {
3423 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003424 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003425
3426 /// PointerTypes - The set of pointer types that will be used in the
3427 /// built-in candidates.
3428 TypeSet PointerTypes;
3429
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003430 /// MemberPointerTypes - The set of member pointer types that will be
3431 /// used in the built-in candidates.
3432 TypeSet MemberPointerTypes;
3433
Douglas Gregora11693b2008-11-12 17:17:38 +00003434 /// EnumerationTypes - The set of enumeration types that will be
3435 /// used in the built-in candidates.
3436 TypeSet EnumerationTypes;
3437
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003438 /// Sema - The semantic analysis instance where we are building the
3439 /// candidate type set.
3440 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003441
Douglas Gregora11693b2008-11-12 17:17:38 +00003442 /// Context - The AST context in which we will build the type sets.
3443 ASTContext &Context;
3444
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003445 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3446 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003447 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003448
3449public:
3450 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003451 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003452
Mike Stump11289f42009-09-09 15:08:12 +00003453 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003454 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003455
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003456 void AddTypesConvertedFrom(QualType Ty,
3457 SourceLocation Loc,
3458 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003459 bool AllowExplicitConversions,
3460 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003461
3462 /// pointer_begin - First pointer type found;
3463 iterator pointer_begin() { return PointerTypes.begin(); }
3464
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003465 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003466 iterator pointer_end() { return PointerTypes.end(); }
3467
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003468 /// member_pointer_begin - First member pointer type found;
3469 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3470
3471 /// member_pointer_end - Past the last member pointer type found;
3472 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3473
Douglas Gregora11693b2008-11-12 17:17:38 +00003474 /// enumeration_begin - First enumeration type found;
3475 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3476
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003477 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003478 iterator enumeration_end() { return EnumerationTypes.end(); }
3479};
3480
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003481/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003482/// the set of pointer types along with any more-qualified variants of
3483/// that type. For example, if @p Ty is "int const *", this routine
3484/// will add "int const *", "int const volatile *", "int const
3485/// restrict *", and "int const volatile restrict *" to the set of
3486/// pointer types. Returns true if the add of @p Ty itself succeeded,
3487/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003488///
3489/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003490bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003491BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3492 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003493
Douglas Gregora11693b2008-11-12 17:17:38 +00003494 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003495 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003496 return false;
3497
John McCall8ccfcb52009-09-24 19:53:00 +00003498 const PointerType *PointerTy = Ty->getAs<PointerType>();
3499 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003500
John McCall8ccfcb52009-09-24 19:53:00 +00003501 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003502 // Don't add qualified variants of arrays. For one, they're not allowed
3503 // (the qualifier would sink to the element type), and for another, the
3504 // only overload situation where it matters is subscript or pointer +- int,
3505 // and those shouldn't have qualifier variants anyway.
3506 if (PointeeTy->isArrayType())
3507 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003508 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003509 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003510 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003511 bool hasVolatile = VisibleQuals.hasVolatile();
3512 bool hasRestrict = VisibleQuals.hasRestrict();
3513
John McCall8ccfcb52009-09-24 19:53:00 +00003514 // Iterate through all strict supersets of BaseCVR.
3515 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3516 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003517 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3518 // in the types.
3519 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3520 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003521 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3522 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003523 }
3524
3525 return true;
3526}
3527
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003528/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3529/// to the set of pointer types along with any more-qualified variants of
3530/// that type. For example, if @p Ty is "int const *", this routine
3531/// will add "int const *", "int const volatile *", "int const
3532/// restrict *", and "int const volatile restrict *" to the set of
3533/// pointer types. Returns true if the add of @p Ty itself succeeded,
3534/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003535///
3536/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003537bool
3538BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3539 QualType Ty) {
3540 // Insert this type.
3541 if (!MemberPointerTypes.insert(Ty))
3542 return false;
3543
John McCall8ccfcb52009-09-24 19:53:00 +00003544 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3545 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003546
John McCall8ccfcb52009-09-24 19:53:00 +00003547 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003548 // Don't add qualified variants of arrays. For one, they're not allowed
3549 // (the qualifier would sink to the element type), and for another, the
3550 // only overload situation where it matters is subscript or pointer +- int,
3551 // and those shouldn't have qualifier variants anyway.
3552 if (PointeeTy->isArrayType())
3553 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003554 const Type *ClassTy = PointerTy->getClass();
3555
3556 // Iterate through all strict supersets of the pointee type's CVR
3557 // qualifiers.
3558 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3559 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3560 if ((CVR | BaseCVR) != CVR) continue;
3561
3562 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3563 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003564 }
3565
3566 return true;
3567}
3568
Douglas Gregora11693b2008-11-12 17:17:38 +00003569/// AddTypesConvertedFrom - Add each of the types to which the type @p
3570/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003571/// primarily interested in pointer types and enumeration types. We also
3572/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003573/// AllowUserConversions is true if we should look at the conversion
3574/// functions of a class type, and AllowExplicitConversions if we
3575/// should also include the explicit conversion functions of a class
3576/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003577void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003578BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003579 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003580 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003581 bool AllowExplicitConversions,
3582 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003583 // Only deal with canonical types.
3584 Ty = Context.getCanonicalType(Ty);
3585
3586 // Look through reference types; they aren't part of the type of an
3587 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003588 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003589 Ty = RefTy->getPointeeType();
3590
3591 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003592 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003593
Sebastian Redl65ae2002009-11-05 16:36:20 +00003594 // If we're dealing with an array type, decay to the pointer.
3595 if (Ty->isArrayType())
3596 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3597
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003598 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003599 QualType PointeeTy = PointerTy->getPointeeType();
3600
3601 // Insert our type, and its more-qualified variants, into the set
3602 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003603 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003604 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003605 } else if (Ty->isMemberPointerType()) {
3606 // Member pointers are far easier, since the pointee can't be converted.
3607 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3608 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003609 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003610 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003611 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003612 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003613 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003614 // No conversion functions in incomplete types.
3615 return;
3616 }
Mike Stump11289f42009-09-09 15:08:12 +00003617
Douglas Gregora11693b2008-11-12 17:17:38 +00003618 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003619 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003620 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003621 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003622 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003623 NamedDecl *D = I.getDecl();
3624 if (isa<UsingShadowDecl>(D))
3625 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003626
Mike Stump11289f42009-09-09 15:08:12 +00003627 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003628 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003629 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003630 continue;
3631
John McCallda4458e2010-03-31 01:36:47 +00003632 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003633 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003634 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003635 VisibleQuals);
3636 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003637 }
3638 }
3639 }
3640}
3641
Douglas Gregor84605ae2009-08-24 13:43:27 +00003642/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3643/// the volatile- and non-volatile-qualified assignment operators for the
3644/// given type to the candidate set.
3645static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3646 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003647 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003648 unsigned NumArgs,
3649 OverloadCandidateSet &CandidateSet) {
3650 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003651
Douglas Gregor84605ae2009-08-24 13:43:27 +00003652 // T& operator=(T&, T)
3653 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3654 ParamTypes[1] = T;
3655 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3656 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003657
Douglas Gregor84605ae2009-08-24 13:43:27 +00003658 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3659 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003660 ParamTypes[0]
3661 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003662 ParamTypes[1] = T;
3663 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003664 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003665 }
3666}
Mike Stump11289f42009-09-09 15:08:12 +00003667
Sebastian Redl1054fae2009-10-25 17:03:50 +00003668/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3669/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003670static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3671 Qualifiers VRQuals;
3672 const RecordType *TyRec;
3673 if (const MemberPointerType *RHSMPType =
3674 ArgExpr->getType()->getAs<MemberPointerType>())
3675 TyRec = cast<RecordType>(RHSMPType->getClass());
3676 else
3677 TyRec = ArgExpr->getType()->getAs<RecordType>();
3678 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003679 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003680 VRQuals.addVolatile();
3681 VRQuals.addRestrict();
3682 return VRQuals;
3683 }
3684
3685 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003686 if (!ClassDecl->hasDefinition())
3687 return VRQuals;
3688
John McCallad371252010-01-20 00:46:10 +00003689 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003690 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003691
John McCallad371252010-01-20 00:46:10 +00003692 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003693 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003694 NamedDecl *D = I.getDecl();
3695 if (isa<UsingShadowDecl>(D))
3696 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3697 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003698 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3699 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3700 CanTy = ResTypeRef->getPointeeType();
3701 // Need to go down the pointer/mempointer chain and add qualifiers
3702 // as see them.
3703 bool done = false;
3704 while (!done) {
3705 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3706 CanTy = ResTypePtr->getPointeeType();
3707 else if (const MemberPointerType *ResTypeMPtr =
3708 CanTy->getAs<MemberPointerType>())
3709 CanTy = ResTypeMPtr->getPointeeType();
3710 else
3711 done = true;
3712 if (CanTy.isVolatileQualified())
3713 VRQuals.addVolatile();
3714 if (CanTy.isRestrictQualified())
3715 VRQuals.addRestrict();
3716 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3717 return VRQuals;
3718 }
3719 }
3720 }
3721 return VRQuals;
3722}
3723
Douglas Gregord08452f2008-11-19 15:42:04 +00003724/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3725/// operator overloads to the candidate set (C++ [over.built]), based
3726/// on the operator @p Op and the arguments given. For example, if the
3727/// operator is a binary '+', this routine might add "int
3728/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003729void
Mike Stump11289f42009-09-09 15:08:12 +00003730Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003731 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003732 Expr **Args, unsigned NumArgs,
3733 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003734 // The set of "promoted arithmetic types", which are the arithmetic
3735 // types are that preserved by promotion (C++ [over.built]p2). Note
3736 // that the first few of these types are the promoted integral
3737 // types; these types need to be first.
3738 // FIXME: What about complex?
3739 const unsigned FirstIntegralType = 0;
3740 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003741 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003742 LastPromotedIntegralType = 13;
3743 const unsigned FirstPromotedArithmeticType = 7,
3744 LastPromotedArithmeticType = 16;
3745 const unsigned NumArithmeticTypes = 16;
3746 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003747 Context.BoolTy, Context.CharTy, Context.WCharTy,
3748// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003749 Context.SignedCharTy, Context.ShortTy,
3750 Context.UnsignedCharTy, Context.UnsignedShortTy,
3751 Context.IntTy, Context.LongTy, Context.LongLongTy,
3752 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3753 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3754 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003755 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3756 "Invalid first promoted integral type");
3757 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3758 == Context.UnsignedLongLongTy &&
3759 "Invalid last promoted integral type");
3760 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3761 "Invalid first promoted arithmetic type");
3762 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3763 == Context.LongDoubleTy &&
3764 "Invalid last promoted arithmetic type");
3765
Douglas Gregora11693b2008-11-12 17:17:38 +00003766 // Find all of the types that the arguments can convert to, but only
3767 // if the operator we're looking at has built-in operator candidates
3768 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003769 Qualifiers VisibleTypeConversionsQuals;
3770 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003771 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3772 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3773
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003774 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003775 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3776 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003777 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003778 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003779 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003780 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003781 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003782 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003783 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003784 true,
3785 (Op == OO_Exclaim ||
3786 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003787 Op == OO_PipePipe),
3788 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003789 }
3790
3791 bool isComparison = false;
3792 switch (Op) {
3793 case OO_None:
3794 case NUM_OVERLOADED_OPERATORS:
3795 assert(false && "Expected an overloaded operator");
3796 break;
3797
Douglas Gregord08452f2008-11-19 15:42:04 +00003798 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003799 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003800 goto UnaryStar;
3801 else
3802 goto BinaryStar;
3803 break;
3804
3805 case OO_Plus: // '+' is either unary or binary
3806 if (NumArgs == 1)
3807 goto UnaryPlus;
3808 else
3809 goto BinaryPlus;
3810 break;
3811
3812 case OO_Minus: // '-' is either unary or binary
3813 if (NumArgs == 1)
3814 goto UnaryMinus;
3815 else
3816 goto BinaryMinus;
3817 break;
3818
3819 case OO_Amp: // '&' is either unary or binary
3820 if (NumArgs == 1)
3821 goto UnaryAmp;
3822 else
3823 goto BinaryAmp;
3824
3825 case OO_PlusPlus:
3826 case OO_MinusMinus:
3827 // C++ [over.built]p3:
3828 //
3829 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3830 // is either volatile or empty, there exist candidate operator
3831 // functions of the form
3832 //
3833 // VQ T& operator++(VQ T&);
3834 // T operator++(VQ T&, int);
3835 //
3836 // C++ [over.built]p4:
3837 //
3838 // For every pair (T, VQ), where T is an arithmetic type other
3839 // than bool, and VQ is either volatile or empty, there exist
3840 // candidate operator functions of the form
3841 //
3842 // VQ T& operator--(VQ T&);
3843 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003844 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003845 Arith < NumArithmeticTypes; ++Arith) {
3846 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003847 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003848 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003849
3850 // Non-volatile version.
3851 if (NumArgs == 1)
3852 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3853 else
3854 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003855 // heuristic to reduce number of builtin candidates in the set.
3856 // Add volatile version only if there are conversions to a volatile type.
3857 if (VisibleTypeConversionsQuals.hasVolatile()) {
3858 // Volatile version
3859 ParamTypes[0]
3860 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3861 if (NumArgs == 1)
3862 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3863 else
3864 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3865 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003866 }
3867
3868 // C++ [over.built]p5:
3869 //
3870 // For every pair (T, VQ), where T is a cv-qualified or
3871 // cv-unqualified object type, and VQ is either volatile or
3872 // empty, there exist candidate operator functions of the form
3873 //
3874 // T*VQ& operator++(T*VQ&);
3875 // T*VQ& operator--(T*VQ&);
3876 // T* operator++(T*VQ&, int);
3877 // T* operator--(T*VQ&, int);
3878 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3879 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3880 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003881 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003882 continue;
3883
Mike Stump11289f42009-09-09 15:08:12 +00003884 QualType ParamTypes[2] = {
3885 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003886 };
Mike Stump11289f42009-09-09 15:08:12 +00003887
Douglas Gregord08452f2008-11-19 15:42:04 +00003888 // Without volatile
3889 if (NumArgs == 1)
3890 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3891 else
3892 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3893
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003894 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3895 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003896 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003897 ParamTypes[0]
3898 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003899 if (NumArgs == 1)
3900 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3901 else
3902 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3903 }
3904 }
3905 break;
3906
3907 UnaryStar:
3908 // C++ [over.built]p6:
3909 // For every cv-qualified or cv-unqualified object type T, there
3910 // exist candidate operator functions of the form
3911 //
3912 // T& operator*(T*);
3913 //
3914 // C++ [over.built]p7:
3915 // For every function type T, there exist candidate operator
3916 // functions of the form
3917 // T& operator*(T*);
3918 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3919 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3920 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003921 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003922 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003923 &ParamTy, Args, 1, CandidateSet);
3924 }
3925 break;
3926
3927 UnaryPlus:
3928 // C++ [over.built]p8:
3929 // For every type T, there exist candidate operator functions of
3930 // the form
3931 //
3932 // T* operator+(T*);
3933 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3934 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3935 QualType ParamTy = *Ptr;
3936 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3937 }
Mike Stump11289f42009-09-09 15:08:12 +00003938
Douglas Gregord08452f2008-11-19 15:42:04 +00003939 // Fall through
3940
3941 UnaryMinus:
3942 // C++ [over.built]p9:
3943 // For every promoted arithmetic type T, there exist candidate
3944 // operator functions of the form
3945 //
3946 // T operator+(T);
3947 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003948 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003949 Arith < LastPromotedArithmeticType; ++Arith) {
3950 QualType ArithTy = ArithmeticTypes[Arith];
3951 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3952 }
3953 break;
3954
3955 case OO_Tilde:
3956 // C++ [over.built]p10:
3957 // For every promoted integral type T, there exist candidate
3958 // operator functions of the form
3959 //
3960 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003961 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003962 Int < LastPromotedIntegralType; ++Int) {
3963 QualType IntTy = ArithmeticTypes[Int];
3964 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3965 }
3966 break;
3967
Douglas Gregora11693b2008-11-12 17:17:38 +00003968 case OO_New:
3969 case OO_Delete:
3970 case OO_Array_New:
3971 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003972 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003973 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003974 break;
3975
3976 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003977 UnaryAmp:
3978 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003979 // C++ [over.match.oper]p3:
3980 // -- For the operator ',', the unary operator '&', or the
3981 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003982 break;
3983
Douglas Gregor84605ae2009-08-24 13:43:27 +00003984 case OO_EqualEqual:
3985 case OO_ExclaimEqual:
3986 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003987 // For every pointer to member type T, there exist candidate operator
3988 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003989 //
3990 // bool operator==(T,T);
3991 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003992 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003993 MemPtr = CandidateTypes.member_pointer_begin(),
3994 MemPtrEnd = CandidateTypes.member_pointer_end();
3995 MemPtr != MemPtrEnd;
3996 ++MemPtr) {
3997 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3998 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3999 }
Mike Stump11289f42009-09-09 15:08:12 +00004000
Douglas Gregor84605ae2009-08-24 13:43:27 +00004001 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004002
Douglas Gregora11693b2008-11-12 17:17:38 +00004003 case OO_Less:
4004 case OO_Greater:
4005 case OO_LessEqual:
4006 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004007 // C++ [over.built]p15:
4008 //
4009 // For every pointer or enumeration type T, there exist
4010 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004011 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004012 // bool operator<(T, T);
4013 // bool operator>(T, T);
4014 // bool operator<=(T, T);
4015 // bool operator>=(T, T);
4016 // bool operator==(T, T);
4017 // bool operator!=(T, T);
4018 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4019 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4020 QualType ParamTypes[2] = { *Ptr, *Ptr };
4021 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4022 }
Mike Stump11289f42009-09-09 15:08:12 +00004023 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004024 = CandidateTypes.enumeration_begin();
4025 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4026 QualType ParamTypes[2] = { *Enum, *Enum };
4027 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4028 }
4029
4030 // Fall through.
4031 isComparison = true;
4032
Douglas Gregord08452f2008-11-19 15:42:04 +00004033 BinaryPlus:
4034 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004035 if (!isComparison) {
4036 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4037
4038 // C++ [over.built]p13:
4039 //
4040 // For every cv-qualified or cv-unqualified object type T
4041 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004042 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004043 // T* operator+(T*, ptrdiff_t);
4044 // T& operator[](T*, ptrdiff_t); [BELOW]
4045 // T* operator-(T*, ptrdiff_t);
4046 // T* operator+(ptrdiff_t, T*);
4047 // T& operator[](ptrdiff_t, T*); [BELOW]
4048 //
4049 // C++ [over.built]p14:
4050 //
4051 // For every T, where T is a pointer to object type, there
4052 // exist candidate operator functions of the form
4053 //
4054 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004055 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004056 = CandidateTypes.pointer_begin();
4057 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4058 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4059
4060 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4061 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4062
4063 if (Op == OO_Plus) {
4064 // T* operator+(ptrdiff_t, T*);
4065 ParamTypes[0] = ParamTypes[1];
4066 ParamTypes[1] = *Ptr;
4067 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4068 } else {
4069 // ptrdiff_t operator-(T, T);
4070 ParamTypes[1] = *Ptr;
4071 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4072 Args, 2, CandidateSet);
4073 }
4074 }
4075 }
4076 // Fall through
4077
Douglas Gregora11693b2008-11-12 17:17:38 +00004078 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004079 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004080 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004081 // C++ [over.built]p12:
4082 //
4083 // For every pair of promoted arithmetic types L and R, there
4084 // exist candidate operator functions of the form
4085 //
4086 // LR operator*(L, R);
4087 // LR operator/(L, R);
4088 // LR operator+(L, R);
4089 // LR operator-(L, R);
4090 // bool operator<(L, R);
4091 // bool operator>(L, R);
4092 // bool operator<=(L, R);
4093 // bool operator>=(L, R);
4094 // bool operator==(L, R);
4095 // bool operator!=(L, R);
4096 //
4097 // where LR is the result of the usual arithmetic conversions
4098 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004099 //
4100 // C++ [over.built]p24:
4101 //
4102 // For every pair of promoted arithmetic types L and R, there exist
4103 // candidate operator functions of the form
4104 //
4105 // LR operator?(bool, L, R);
4106 //
4107 // where LR is the result of the usual arithmetic conversions
4108 // between types L and R.
4109 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004110 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004111 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004112 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004113 Right < LastPromotedArithmeticType; ++Right) {
4114 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004115 QualType Result
4116 = isComparison
4117 ? Context.BoolTy
4118 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004119 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4120 }
4121 }
4122 break;
4123
4124 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004125 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004126 case OO_Caret:
4127 case OO_Pipe:
4128 case OO_LessLess:
4129 case OO_GreaterGreater:
4130 // C++ [over.built]p17:
4131 //
4132 // For every pair of promoted integral types L and R, there
4133 // exist candidate operator functions of the form
4134 //
4135 // LR operator%(L, R);
4136 // LR operator&(L, R);
4137 // LR operator^(L, R);
4138 // LR operator|(L, R);
4139 // L operator<<(L, R);
4140 // L operator>>(L, R);
4141 //
4142 // where LR is the result of the usual arithmetic conversions
4143 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004144 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004145 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004146 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004147 Right < LastPromotedIntegralType; ++Right) {
4148 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4149 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4150 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004151 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004152 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4153 }
4154 }
4155 break;
4156
4157 case OO_Equal:
4158 // C++ [over.built]p20:
4159 //
4160 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004161 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004162 // empty, there exist candidate operator functions of the form
4163 //
4164 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004165 for (BuiltinCandidateTypeSet::iterator
4166 Enum = CandidateTypes.enumeration_begin(),
4167 EnumEnd = CandidateTypes.enumeration_end();
4168 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004169 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004170 CandidateSet);
4171 for (BuiltinCandidateTypeSet::iterator
4172 MemPtr = CandidateTypes.member_pointer_begin(),
4173 MemPtrEnd = CandidateTypes.member_pointer_end();
4174 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004175 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004176 CandidateSet);
4177 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004178
4179 case OO_PlusEqual:
4180 case OO_MinusEqual:
4181 // C++ [over.built]p19:
4182 //
4183 // For every pair (T, VQ), where T is any type and VQ is either
4184 // volatile or empty, there exist candidate operator functions
4185 // of the form
4186 //
4187 // T*VQ& operator=(T*VQ&, T*);
4188 //
4189 // C++ [over.built]p21:
4190 //
4191 // For every pair (T, VQ), where T is a cv-qualified or
4192 // cv-unqualified object type and VQ is either volatile or
4193 // empty, there exist candidate operator functions of the form
4194 //
4195 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4196 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4197 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4198 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4199 QualType ParamTypes[2];
4200 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4201
4202 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004203 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004204 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4205 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004206
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004207 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4208 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004209 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004210 ParamTypes[0]
4211 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004212 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4213 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004214 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004215 }
4216 // Fall through.
4217
4218 case OO_StarEqual:
4219 case OO_SlashEqual:
4220 // C++ [over.built]p18:
4221 //
4222 // For every triple (L, VQ, R), where L is an arithmetic type,
4223 // VQ is either volatile or empty, and R is a promoted
4224 // arithmetic type, there exist candidate operator functions of
4225 // the form
4226 //
4227 // VQ L& operator=(VQ L&, R);
4228 // VQ L& operator*=(VQ L&, R);
4229 // VQ L& operator/=(VQ L&, R);
4230 // VQ L& operator+=(VQ L&, R);
4231 // VQ L& operator-=(VQ L&, R);
4232 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004233 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004234 Right < LastPromotedArithmeticType; ++Right) {
4235 QualType ParamTypes[2];
4236 ParamTypes[1] = ArithmeticTypes[Right];
4237
4238 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004239 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004240 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4241 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004242
4243 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004244 if (VisibleTypeConversionsQuals.hasVolatile()) {
4245 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4246 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4247 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4248 /*IsAssigmentOperator=*/Op == OO_Equal);
4249 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004250 }
4251 }
4252 break;
4253
4254 case OO_PercentEqual:
4255 case OO_LessLessEqual:
4256 case OO_GreaterGreaterEqual:
4257 case OO_AmpEqual:
4258 case OO_CaretEqual:
4259 case OO_PipeEqual:
4260 // C++ [over.built]p22:
4261 //
4262 // For every triple (L, VQ, R), where L is an integral type, VQ
4263 // is either volatile or empty, and R is a promoted integral
4264 // type, there exist candidate operator functions of the form
4265 //
4266 // VQ L& operator%=(VQ L&, R);
4267 // VQ L& operator<<=(VQ L&, R);
4268 // VQ L& operator>>=(VQ L&, R);
4269 // VQ L& operator&=(VQ L&, R);
4270 // VQ L& operator^=(VQ L&, R);
4271 // VQ L& operator|=(VQ L&, R);
4272 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004273 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004274 Right < LastPromotedIntegralType; ++Right) {
4275 QualType ParamTypes[2];
4276 ParamTypes[1] = ArithmeticTypes[Right];
4277
4278 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004279 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004280 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004281 if (VisibleTypeConversionsQuals.hasVolatile()) {
4282 // Add this built-in operator as a candidate (VQ is 'volatile').
4283 ParamTypes[0] = ArithmeticTypes[Left];
4284 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4285 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4286 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4287 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004288 }
4289 }
4290 break;
4291
Douglas Gregord08452f2008-11-19 15:42:04 +00004292 case OO_Exclaim: {
4293 // C++ [over.operator]p23:
4294 //
4295 // There also exist candidate operator functions of the form
4296 //
Mike Stump11289f42009-09-09 15:08:12 +00004297 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004298 // bool operator&&(bool, bool); [BELOW]
4299 // bool operator||(bool, bool); [BELOW]
4300 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004301 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4302 /*IsAssignmentOperator=*/false,
4303 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004304 break;
4305 }
4306
Douglas Gregora11693b2008-11-12 17:17:38 +00004307 case OO_AmpAmp:
4308 case OO_PipePipe: {
4309 // C++ [over.operator]p23:
4310 //
4311 // There also exist candidate operator functions of the form
4312 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004313 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004314 // bool operator&&(bool, bool);
4315 // bool operator||(bool, bool);
4316 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004317 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4318 /*IsAssignmentOperator=*/false,
4319 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004320 break;
4321 }
4322
4323 case OO_Subscript:
4324 // C++ [over.built]p13:
4325 //
4326 // For every cv-qualified or cv-unqualified object type T there
4327 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004328 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004329 // T* operator+(T*, ptrdiff_t); [ABOVE]
4330 // T& operator[](T*, ptrdiff_t);
4331 // T* operator-(T*, ptrdiff_t); [ABOVE]
4332 // T* operator+(ptrdiff_t, T*); [ABOVE]
4333 // T& operator[](ptrdiff_t, T*);
4334 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4335 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4336 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004337 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004338 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004339
4340 // T& operator[](T*, ptrdiff_t)
4341 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4342
4343 // T& operator[](ptrdiff_t, T*);
4344 ParamTypes[0] = ParamTypes[1];
4345 ParamTypes[1] = *Ptr;
4346 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4347 }
4348 break;
4349
4350 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004351 // C++ [over.built]p11:
4352 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4353 // C1 is the same type as C2 or is a derived class of C2, T is an object
4354 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4355 // there exist candidate operator functions of the form
4356 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4357 // where CV12 is the union of CV1 and CV2.
4358 {
4359 for (BuiltinCandidateTypeSet::iterator Ptr =
4360 CandidateTypes.pointer_begin();
4361 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4362 QualType C1Ty = (*Ptr);
4363 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004364 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004365 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004366 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004367 if (!isa<RecordType>(C1))
4368 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004369 // heuristic to reduce number of builtin candidates in the set.
4370 // Add volatile/restrict version only if there are conversions to a
4371 // volatile/restrict type.
4372 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4373 continue;
4374 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4375 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004376 }
4377 for (BuiltinCandidateTypeSet::iterator
4378 MemPtr = CandidateTypes.member_pointer_begin(),
4379 MemPtrEnd = CandidateTypes.member_pointer_end();
4380 MemPtr != MemPtrEnd; ++MemPtr) {
4381 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4382 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004383 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004384 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4385 break;
4386 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4387 // build CV12 T&
4388 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004389 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4390 T.isVolatileQualified())
4391 continue;
4392 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4393 T.isRestrictQualified())
4394 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004395 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004396 QualType ResultTy = Context.getLValueReferenceType(T);
4397 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4398 }
4399 }
4400 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004401 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004402
4403 case OO_Conditional:
4404 // Note that we don't consider the first argument, since it has been
4405 // contextually converted to bool long ago. The candidates below are
4406 // therefore added as binary.
4407 //
4408 // C++ [over.built]p24:
4409 // For every type T, where T is a pointer or pointer-to-member type,
4410 // there exist candidate operator functions of the form
4411 //
4412 // T operator?(bool, T, T);
4413 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004414 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4415 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4416 QualType ParamTypes[2] = { *Ptr, *Ptr };
4417 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4418 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004419 for (BuiltinCandidateTypeSet::iterator Ptr =
4420 CandidateTypes.member_pointer_begin(),
4421 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4422 QualType ParamTypes[2] = { *Ptr, *Ptr };
4423 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4424 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004425 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004426 }
4427}
4428
Douglas Gregore254f902009-02-04 00:32:51 +00004429/// \brief Add function candidates found via argument-dependent lookup
4430/// to the set of overloading candidates.
4431///
4432/// This routine performs argument-dependent name lookup based on the
4433/// given function name (which may also be an operator name) and adds
4434/// all of the overload candidates found by ADL to the overload
4435/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004436void
Douglas Gregore254f902009-02-04 00:32:51 +00004437Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004438 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004439 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004440 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004441 OverloadCandidateSet& CandidateSet,
4442 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004443 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004444
John McCall91f61fc2010-01-26 06:04:06 +00004445 // FIXME: This approach for uniquing ADL results (and removing
4446 // redundant candidates from the set) relies on pointer-equality,
4447 // which means we need to key off the canonical decl. However,
4448 // always going back to the canonical decl might not get us the
4449 // right set of default arguments. What default arguments are
4450 // we supposed to consider on ADL candidates, anyway?
4451
Douglas Gregorcabea402009-09-22 15:41:20 +00004452 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004453 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004454
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004455 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004456 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4457 CandEnd = CandidateSet.end();
4458 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004459 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004460 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004461 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004462 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004463 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004464
4465 // For each of the ADL candidates we found, add it to the overload
4466 // set.
John McCall8fe68082010-01-26 07:16:45 +00004467 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004468 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004469 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004470 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004471 continue;
4472
John McCalla0296f72010-03-19 07:35:19 +00004473 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004474 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004475 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004476 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004477 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004478 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004479 }
Douglas Gregore254f902009-02-04 00:32:51 +00004480}
4481
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004482/// isBetterOverloadCandidate - Determines whether the first overload
4483/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004484bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004485Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004486 const OverloadCandidate& Cand2,
4487 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004488 // Define viable functions to be better candidates than non-viable
4489 // functions.
4490 if (!Cand2.Viable)
4491 return Cand1.Viable;
4492 else if (!Cand1.Viable)
4493 return false;
4494
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004495 // C++ [over.match.best]p1:
4496 //
4497 // -- if F is a static member function, ICS1(F) is defined such
4498 // that ICS1(F) is neither better nor worse than ICS1(G) for
4499 // any function G, and, symmetrically, ICS1(G) is neither
4500 // better nor worse than ICS1(F).
4501 unsigned StartArg = 0;
4502 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4503 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004504
Douglas Gregord3cb3562009-07-07 23:38:56 +00004505 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004506 // A viable function F1 is defined to be a better function than another
4507 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004508 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004509 unsigned NumArgs = Cand1.Conversions.size();
4510 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4511 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004512 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004513 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4514 Cand2.Conversions[ArgIdx])) {
4515 case ImplicitConversionSequence::Better:
4516 // Cand1 has a better conversion sequence.
4517 HasBetterConversion = true;
4518 break;
4519
4520 case ImplicitConversionSequence::Worse:
4521 // Cand1 can't be better than Cand2.
4522 return false;
4523
4524 case ImplicitConversionSequence::Indistinguishable:
4525 // Do nothing.
4526 break;
4527 }
4528 }
4529
Mike Stump11289f42009-09-09 15:08:12 +00004530 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004531 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004532 if (HasBetterConversion)
4533 return true;
4534
Mike Stump11289f42009-09-09 15:08:12 +00004535 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004536 // specialization, or, if not that,
4537 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4538 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4539 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004540
4541 // -- F1 and F2 are function template specializations, and the function
4542 // template for F1 is more specialized than the template for F2
4543 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004544 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004545 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4546 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004547 if (FunctionTemplateDecl *BetterTemplate
4548 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4549 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004550 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004551 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4552 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004553 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004554
Douglas Gregora1f013e2008-11-07 22:36:19 +00004555 // -- the context is an initialization by user-defined conversion
4556 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4557 // from the return type of F1 to the destination type (i.e.,
4558 // the type of the entity being initialized) is a better
4559 // conversion sequence than the standard conversion sequence
4560 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004561 if (Cand1.Function && Cand2.Function &&
4562 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004563 isa<CXXConversionDecl>(Cand2.Function)) {
4564 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4565 Cand2.FinalConversion)) {
4566 case ImplicitConversionSequence::Better:
4567 // Cand1 has a better conversion sequence.
4568 return true;
4569
4570 case ImplicitConversionSequence::Worse:
4571 // Cand1 can't be better than Cand2.
4572 return false;
4573
4574 case ImplicitConversionSequence::Indistinguishable:
4575 // Do nothing
4576 break;
4577 }
4578 }
4579
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004580 return false;
4581}
4582
Mike Stump11289f42009-09-09 15:08:12 +00004583/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004584/// within an overload candidate set.
4585///
4586/// \param CandidateSet the set of candidate functions.
4587///
4588/// \param Loc the location of the function name (or operator symbol) for
4589/// which overload resolution occurs.
4590///
Mike Stump11289f42009-09-09 15:08:12 +00004591/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004592/// function, Best points to the candidate function found.
4593///
4594/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004595OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4596 SourceLocation Loc,
4597 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004598 // Find the best viable function.
4599 Best = CandidateSet.end();
4600 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4601 Cand != CandidateSet.end(); ++Cand) {
4602 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004603 if (Best == CandidateSet.end() ||
4604 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004605 Best = Cand;
4606 }
4607 }
4608
4609 // If we didn't find any viable functions, abort.
4610 if (Best == CandidateSet.end())
4611 return OR_No_Viable_Function;
4612
4613 // Make sure that this function is better than every other viable
4614 // function. If not, we have an ambiguity.
4615 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4616 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004617 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004618 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004619 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004620 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004621 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004622 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004623 }
Mike Stump11289f42009-09-09 15:08:12 +00004624
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004625 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004626 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004627 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004628 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004629 return OR_Deleted;
4630
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004631 // C++ [basic.def.odr]p2:
4632 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004633 // when referred to from a potentially-evaluated expression. [Note: this
4634 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004635 // (clause 13), user-defined conversions (12.3.2), allocation function for
4636 // placement new (5.3.4), as well as non-default initialization (8.5).
4637 if (Best->Function)
4638 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004639 return OR_Success;
4640}
4641
John McCall53262c92010-01-12 02:15:36 +00004642namespace {
4643
4644enum OverloadCandidateKind {
4645 oc_function,
4646 oc_method,
4647 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004648 oc_function_template,
4649 oc_method_template,
4650 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004651 oc_implicit_default_constructor,
4652 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004653 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004654};
4655
John McCalle1ac8d12010-01-13 00:25:19 +00004656OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4657 FunctionDecl *Fn,
4658 std::string &Description) {
4659 bool isTemplate = false;
4660
4661 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4662 isTemplate = true;
4663 Description = S.getTemplateArgumentBindingsText(
4664 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4665 }
John McCallfd0b2f82010-01-06 09:43:14 +00004666
4667 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004668 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004669 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004670
John McCall53262c92010-01-12 02:15:36 +00004671 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4672 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004673 }
4674
4675 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4676 // This actually gets spelled 'candidate function' for now, but
4677 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004678 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004679 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004680
4681 assert(Meth->isCopyAssignment()
4682 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004683 return oc_implicit_copy_assignment;
4684 }
4685
John McCalle1ac8d12010-01-13 00:25:19 +00004686 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004687}
4688
4689} // end anonymous namespace
4690
4691// Notes the location of an overload candidate.
4692void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004693 std::string FnDesc;
4694 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4695 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4696 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004697}
4698
John McCall0d1da222010-01-12 00:44:57 +00004699/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4700/// "lead" diagnostic; it will be given two arguments, the source and
4701/// target types of the conversion.
4702void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4703 SourceLocation CaretLoc,
4704 const PartialDiagnostic &PDiag) {
4705 Diag(CaretLoc, PDiag)
4706 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4707 for (AmbiguousConversionSequence::const_iterator
4708 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4709 NoteOverloadCandidate(*I);
4710 }
John McCall12f97bc2010-01-08 04:41:39 +00004711}
4712
John McCall0d1da222010-01-12 00:44:57 +00004713namespace {
4714
John McCall6a61b522010-01-13 09:16:55 +00004715void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4716 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4717 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004718 assert(Cand->Function && "for now, candidate must be a function");
4719 FunctionDecl *Fn = Cand->Function;
4720
4721 // There's a conversion slot for the object argument if this is a
4722 // non-constructor method. Note that 'I' corresponds the
4723 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004724 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004725 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004726 if (I == 0)
4727 isObjectArgument = true;
4728 else
4729 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004730 }
4731
John McCalle1ac8d12010-01-13 00:25:19 +00004732 std::string FnDesc;
4733 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4734
John McCall6a61b522010-01-13 09:16:55 +00004735 Expr *FromExpr = Conv.Bad.FromExpr;
4736 QualType FromTy = Conv.Bad.getFromType();
4737 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004738
John McCallfb7ad0f2010-02-02 02:42:52 +00004739 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004740 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004741 Expr *E = FromExpr->IgnoreParens();
4742 if (isa<UnaryOperator>(E))
4743 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004744 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004745
4746 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4747 << (unsigned) FnKind << FnDesc
4748 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4749 << ToTy << Name << I+1;
4750 return;
4751 }
4752
John McCall6d174642010-01-23 08:10:49 +00004753 // Do some hand-waving analysis to see if the non-viability is due
4754 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004755 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4756 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4757 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4758 CToTy = RT->getPointeeType();
4759 else {
4760 // TODO: detect and diagnose the full richness of const mismatches.
4761 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4762 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4763 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4764 }
4765
4766 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4767 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4768 // It is dumb that we have to do this here.
4769 while (isa<ArrayType>(CFromTy))
4770 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4771 while (isa<ArrayType>(CToTy))
4772 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4773
4774 Qualifiers FromQs = CFromTy.getQualifiers();
4775 Qualifiers ToQs = CToTy.getQualifiers();
4776
4777 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4778 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4779 << (unsigned) FnKind << FnDesc
4780 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4781 << FromTy
4782 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4783 << (unsigned) isObjectArgument << I+1;
4784 return;
4785 }
4786
4787 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4788 assert(CVR && "unexpected qualifiers mismatch");
4789
4790 if (isObjectArgument) {
4791 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4792 << (unsigned) FnKind << FnDesc
4793 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4794 << FromTy << (CVR - 1);
4795 } else {
4796 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4797 << (unsigned) FnKind << FnDesc
4798 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4799 << FromTy << (CVR - 1) << I+1;
4800 }
4801 return;
4802 }
4803
John McCall6d174642010-01-23 08:10:49 +00004804 // Diagnose references or pointers to incomplete types differently,
4805 // since it's far from impossible that the incompleteness triggered
4806 // the failure.
4807 QualType TempFromTy = FromTy.getNonReferenceType();
4808 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4809 TempFromTy = PTy->getPointeeType();
4810 if (TempFromTy->isIncompleteType()) {
4811 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4812 << (unsigned) FnKind << FnDesc
4813 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4814 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4815 return;
4816 }
4817
John McCall47000992010-01-14 03:28:57 +00004818 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004819 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4820 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004821 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004822 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004823}
4824
4825void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4826 unsigned NumFormalArgs) {
4827 // TODO: treat calls to a missing default constructor as a special case
4828
4829 FunctionDecl *Fn = Cand->Function;
4830 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4831
4832 unsigned MinParams = Fn->getMinRequiredArguments();
4833
4834 // at least / at most / exactly
4835 unsigned mode, modeCount;
4836 if (NumFormalArgs < MinParams) {
4837 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4838 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4839 mode = 0; // "at least"
4840 else
4841 mode = 2; // "exactly"
4842 modeCount = MinParams;
4843 } else {
4844 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4845 if (MinParams != FnTy->getNumArgs())
4846 mode = 1; // "at most"
4847 else
4848 mode = 2; // "exactly"
4849 modeCount = FnTy->getNumArgs();
4850 }
4851
4852 std::string Description;
4853 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4854
4855 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4856 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004857}
4858
John McCall8b9ed552010-02-01 18:53:26 +00004859/// Diagnose a failed template-argument deduction.
4860void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4861 Expr **Args, unsigned NumArgs) {
4862 FunctionDecl *Fn = Cand->Function; // pattern
4863
4864 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4865 Cand->DeductionFailure.TemplateParameter);
4866
4867 switch (Cand->DeductionFailure.Result) {
4868 case Sema::TDK_Success:
4869 llvm_unreachable("TDK_success while diagnosing bad deduction");
4870
4871 case Sema::TDK_Incomplete: {
4872 NamedDecl *ParamD;
4873 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4874 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4875 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4876 assert(ParamD && "no parameter found for incomplete deduction result");
4877 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4878 << ParamD->getDeclName();
4879 return;
4880 }
4881
4882 // TODO: diagnose these individually, then kill off
4883 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4884 case Sema::TDK_InstantiationDepth:
4885 case Sema::TDK_Inconsistent:
4886 case Sema::TDK_InconsistentQuals:
4887 case Sema::TDK_SubstitutionFailure:
4888 case Sema::TDK_NonDeducedMismatch:
4889 case Sema::TDK_TooManyArguments:
4890 case Sema::TDK_TooFewArguments:
4891 case Sema::TDK_InvalidExplicitArguments:
4892 case Sema::TDK_FailedOverloadResolution:
4893 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4894 return;
4895 }
4896}
4897
4898/// Generates a 'note' diagnostic for an overload candidate. We've
4899/// already generated a primary error at the call site.
4900///
4901/// It really does need to be a single diagnostic with its caret
4902/// pointed at the candidate declaration. Yes, this creates some
4903/// major challenges of technical writing. Yes, this makes pointing
4904/// out problems with specific arguments quite awkward. It's still
4905/// better than generating twenty screens of text for every failed
4906/// overload.
4907///
4908/// It would be great to be able to express per-candidate problems
4909/// more richly for those diagnostic clients that cared, but we'd
4910/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004911void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4912 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004913 FunctionDecl *Fn = Cand->Function;
4914
John McCall12f97bc2010-01-08 04:41:39 +00004915 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004916 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004917 std::string FnDesc;
4918 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004919
4920 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004921 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004922 return;
John McCall12f97bc2010-01-08 04:41:39 +00004923 }
4924
John McCalle1ac8d12010-01-13 00:25:19 +00004925 // We don't really have anything else to say about viable candidates.
4926 if (Cand->Viable) {
4927 S.NoteOverloadCandidate(Fn);
4928 return;
4929 }
John McCall0d1da222010-01-12 00:44:57 +00004930
John McCall6a61b522010-01-13 09:16:55 +00004931 switch (Cand->FailureKind) {
4932 case ovl_fail_too_many_arguments:
4933 case ovl_fail_too_few_arguments:
4934 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004935
John McCall6a61b522010-01-13 09:16:55 +00004936 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004937 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4938
John McCallfe796dd2010-01-23 05:17:32 +00004939 case ovl_fail_trivial_conversion:
4940 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004941 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00004942 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004943
John McCall65eb8792010-02-25 01:37:24 +00004944 case ovl_fail_bad_conversion: {
4945 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4946 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00004947 if (Cand->Conversions[I].isBad())
4948 return DiagnoseBadConversion(S, Cand, I);
4949
4950 // FIXME: this currently happens when we're called from SemaInit
4951 // when user-conversion overload fails. Figure out how to handle
4952 // those conditions and diagnose them well.
4953 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004954 }
John McCall65eb8792010-02-25 01:37:24 +00004955 }
John McCalld3224162010-01-08 00:58:21 +00004956}
4957
4958void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4959 // Desugar the type of the surrogate down to a function type,
4960 // retaining as many typedefs as possible while still showing
4961 // the function type (and, therefore, its parameter types).
4962 QualType FnType = Cand->Surrogate->getConversionType();
4963 bool isLValueReference = false;
4964 bool isRValueReference = false;
4965 bool isPointer = false;
4966 if (const LValueReferenceType *FnTypeRef =
4967 FnType->getAs<LValueReferenceType>()) {
4968 FnType = FnTypeRef->getPointeeType();
4969 isLValueReference = true;
4970 } else if (const RValueReferenceType *FnTypeRef =
4971 FnType->getAs<RValueReferenceType>()) {
4972 FnType = FnTypeRef->getPointeeType();
4973 isRValueReference = true;
4974 }
4975 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4976 FnType = FnTypePtr->getPointeeType();
4977 isPointer = true;
4978 }
4979 // Desugar down to a function type.
4980 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4981 // Reconstruct the pointer/reference as appropriate.
4982 if (isPointer) FnType = S.Context.getPointerType(FnType);
4983 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4984 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4985
4986 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4987 << FnType;
4988}
4989
4990void NoteBuiltinOperatorCandidate(Sema &S,
4991 const char *Opc,
4992 SourceLocation OpLoc,
4993 OverloadCandidate *Cand) {
4994 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4995 std::string TypeStr("operator");
4996 TypeStr += Opc;
4997 TypeStr += "(";
4998 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4999 if (Cand->Conversions.size() == 1) {
5000 TypeStr += ")";
5001 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5002 } else {
5003 TypeStr += ", ";
5004 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5005 TypeStr += ")";
5006 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5007 }
5008}
5009
5010void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5011 OverloadCandidate *Cand) {
5012 unsigned NoOperands = Cand->Conversions.size();
5013 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5014 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005015 if (ICS.isBad()) break; // all meaningless after first invalid
5016 if (!ICS.isAmbiguous()) continue;
5017
5018 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005019 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005020 }
5021}
5022
John McCall3712d9e2010-01-15 23:32:50 +00005023SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5024 if (Cand->Function)
5025 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005026 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005027 return Cand->Surrogate->getLocation();
5028 return SourceLocation();
5029}
5030
John McCallad2587a2010-01-12 00:48:53 +00005031struct CompareOverloadCandidatesForDisplay {
5032 Sema &S;
5033 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005034
5035 bool operator()(const OverloadCandidate *L,
5036 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005037 // Fast-path this check.
5038 if (L == R) return false;
5039
John McCall12f97bc2010-01-08 04:41:39 +00005040 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005041 if (L->Viable) {
5042 if (!R->Viable) return true;
5043
5044 // TODO: introduce a tri-valued comparison for overload
5045 // candidates. Would be more worthwhile if we had a sort
5046 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005047 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5048 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005049 } else if (R->Viable)
5050 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005051
John McCall3712d9e2010-01-15 23:32:50 +00005052 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005053
John McCall3712d9e2010-01-15 23:32:50 +00005054 // Criteria by which we can sort non-viable candidates:
5055 if (!L->Viable) {
5056 // 1. Arity mismatches come after other candidates.
5057 if (L->FailureKind == ovl_fail_too_many_arguments ||
5058 L->FailureKind == ovl_fail_too_few_arguments)
5059 return false;
5060 if (R->FailureKind == ovl_fail_too_many_arguments ||
5061 R->FailureKind == ovl_fail_too_few_arguments)
5062 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005063
John McCallfe796dd2010-01-23 05:17:32 +00005064 // 2. Bad conversions come first and are ordered by the number
5065 // of bad conversions and quality of good conversions.
5066 if (L->FailureKind == ovl_fail_bad_conversion) {
5067 if (R->FailureKind != ovl_fail_bad_conversion)
5068 return true;
5069
5070 // If there's any ordering between the defined conversions...
5071 // FIXME: this might not be transitive.
5072 assert(L->Conversions.size() == R->Conversions.size());
5073
5074 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005075 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5076 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005077 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5078 R->Conversions[I])) {
5079 case ImplicitConversionSequence::Better:
5080 leftBetter++;
5081 break;
5082
5083 case ImplicitConversionSequence::Worse:
5084 leftBetter--;
5085 break;
5086
5087 case ImplicitConversionSequence::Indistinguishable:
5088 break;
5089 }
5090 }
5091 if (leftBetter > 0) return true;
5092 if (leftBetter < 0) return false;
5093
5094 } else if (R->FailureKind == ovl_fail_bad_conversion)
5095 return false;
5096
John McCall3712d9e2010-01-15 23:32:50 +00005097 // TODO: others?
5098 }
5099
5100 // Sort everything else by location.
5101 SourceLocation LLoc = GetLocationForCandidate(L);
5102 SourceLocation RLoc = GetLocationForCandidate(R);
5103
5104 // Put candidates without locations (e.g. builtins) at the end.
5105 if (LLoc.isInvalid()) return false;
5106 if (RLoc.isInvalid()) return true;
5107
5108 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005109 }
5110};
5111
John McCallfe796dd2010-01-23 05:17:32 +00005112/// CompleteNonViableCandidate - Normally, overload resolution only
5113/// computes up to the first
5114void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5115 Expr **Args, unsigned NumArgs) {
5116 assert(!Cand->Viable);
5117
5118 // Don't do anything on failures other than bad conversion.
5119 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5120
5121 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005122 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005123 unsigned ConvCount = Cand->Conversions.size();
5124 while (true) {
5125 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5126 ConvIdx++;
5127 if (Cand->Conversions[ConvIdx - 1].isBad())
5128 break;
5129 }
5130
5131 if (ConvIdx == ConvCount)
5132 return;
5133
John McCall65eb8792010-02-25 01:37:24 +00005134 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5135 "remaining conversion is initialized?");
5136
Douglas Gregoradc7a702010-04-16 17:45:54 +00005137 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005138 // operation somehow.
5139 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005140
5141 const FunctionProtoType* Proto;
5142 unsigned ArgIdx = ConvIdx;
5143
5144 if (Cand->IsSurrogate) {
5145 QualType ConvType
5146 = Cand->Surrogate->getConversionType().getNonReferenceType();
5147 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5148 ConvType = ConvPtrType->getPointeeType();
5149 Proto = ConvType->getAs<FunctionProtoType>();
5150 ArgIdx--;
5151 } else if (Cand->Function) {
5152 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5153 if (isa<CXXMethodDecl>(Cand->Function) &&
5154 !isa<CXXConstructorDecl>(Cand->Function))
5155 ArgIdx--;
5156 } else {
5157 // Builtin binary operator with a bad first conversion.
5158 assert(ConvCount <= 3);
5159 for (; ConvIdx != ConvCount; ++ConvIdx)
5160 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005161 = TryCopyInitialization(S, Args[ConvIdx],
5162 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5163 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005164 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005165 return;
5166 }
5167
5168 // Fill in the rest of the conversions.
5169 unsigned NumArgsInProto = Proto->getNumArgs();
5170 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5171 if (ArgIdx < NumArgsInProto)
5172 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005173 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5174 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005175 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005176 else
5177 Cand->Conversions[ConvIdx].setEllipsis();
5178 }
5179}
5180
John McCalld3224162010-01-08 00:58:21 +00005181} // end anonymous namespace
5182
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005183/// PrintOverloadCandidates - When overload resolution fails, prints
5184/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005185/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005186void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005187Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005188 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005189 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005190 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005191 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005192 // Sort the candidates by viability and position. Sorting directly would
5193 // be prohibitive, so we make a set of pointers and sort those.
5194 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5195 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5196 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5197 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005198 Cand != LastCand; ++Cand) {
5199 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005200 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005201 else if (OCD == OCD_AllCandidates) {
5202 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5203 Cands.push_back(Cand);
5204 }
5205 }
5206
John McCallad2587a2010-01-12 00:48:53 +00005207 std::sort(Cands.begin(), Cands.end(),
5208 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005209
John McCall0d1da222010-01-12 00:44:57 +00005210 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005211
John McCall12f97bc2010-01-08 04:41:39 +00005212 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5213 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5214 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005215
John McCalld3224162010-01-08 00:58:21 +00005216 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005217 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005218 else if (Cand->IsSurrogate)
5219 NoteSurrogateCandidate(*this, Cand);
5220
5221 // This a builtin candidate. We do not, in general, want to list
5222 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005223 else if (Cand->Viable) {
5224 // Generally we only see ambiguities including viable builtin
5225 // operators if overload resolution got screwed up by an
5226 // ambiguous user-defined conversion.
5227 //
5228 // FIXME: It's quite possible for different conversions to see
5229 // different ambiguities, though.
5230 if (!ReportedAmbiguousConversions) {
5231 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5232 ReportedAmbiguousConversions = true;
5233 }
John McCalld3224162010-01-08 00:58:21 +00005234
John McCall0d1da222010-01-12 00:44:57 +00005235 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005236 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005237 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005238 }
5239}
5240
John McCalla0296f72010-03-19 07:35:19 +00005241static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005242 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005243 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005244
John McCalla0296f72010-03-19 07:35:19 +00005245 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005246}
5247
Douglas Gregorcd695e52008-11-10 20:40:00 +00005248/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5249/// an overloaded function (C++ [over.over]), where @p From is an
5250/// expression with overloaded function type and @p ToType is the type
5251/// we're trying to resolve to. For example:
5252///
5253/// @code
5254/// int f(double);
5255/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005256///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005257/// int (*pfd)(double) = f; // selects f(double)
5258/// @endcode
5259///
5260/// This routine returns the resulting FunctionDecl if it could be
5261/// resolved, and NULL otherwise. When @p Complain is true, this
5262/// routine will emit diagnostics if there is an error.
5263FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005264Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005265 bool Complain,
5266 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005267 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005268 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005269 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005270 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005271 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005272 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005273 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005274 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005275 FunctionType = MemTypePtr->getPointeeType();
5276 IsMember = true;
5277 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005278
Douglas Gregorcd695e52008-11-10 20:40:00 +00005279 // C++ [over.over]p1:
5280 // [...] [Note: any redundant set of parentheses surrounding the
5281 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005282 // C++ [over.over]p1:
5283 // [...] The overloaded function name can be preceded by the &
5284 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005285 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5286 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5287 if (OvlExpr->hasExplicitTemplateArgs()) {
5288 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5289 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005290 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005291
5292 // We expect a pointer or reference to function, or a function pointer.
5293 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5294 if (!FunctionType->isFunctionType()) {
5295 if (Complain)
5296 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5297 << OvlExpr->getName() << ToType;
5298
5299 return 0;
5300 }
5301
5302 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005303
Douglas Gregorcd695e52008-11-10 20:40:00 +00005304 // Look through all of the overloaded functions, searching for one
5305 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005306 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005307 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5308
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005309 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005310 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5311 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005312 // Look through any using declarations to find the underlying function.
5313 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5314
Douglas Gregorcd695e52008-11-10 20:40:00 +00005315 // C++ [over.over]p3:
5316 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005317 // targets of type "pointer-to-function" or "reference-to-function."
5318 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005319 // type "pointer-to-member-function."
5320 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005321
Mike Stump11289f42009-09-09 15:08:12 +00005322 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005323 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005324 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005325 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005326 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005327 // static when converting to member pointer.
5328 if (Method->isStatic() == IsMember)
5329 continue;
5330 } else if (IsMember)
5331 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005332
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005333 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005334 // If the name is a function template, template argument deduction is
5335 // done (14.8.2.2), and if the argument deduction succeeds, the
5336 // resulting template argument list is used to generate a single
5337 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005338 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005339 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005340 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005341 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005342 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005343 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005344 FunctionType, Specialization, Info)) {
5345 // FIXME: make a note of the failed deduction for diagnostics.
5346 (void)Result;
5347 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005348 // FIXME: If the match isn't exact, shouldn't we just drop this as
5349 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005350 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005351 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005352 Matches.push_back(std::make_pair(I.getPair(),
5353 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005354 }
John McCalld14a8642009-11-21 08:51:07 +00005355
5356 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005357 }
Mike Stump11289f42009-09-09 15:08:12 +00005358
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005359 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005360 // Skip non-static functions when converting to pointer, and static
5361 // when converting to member pointer.
5362 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005363 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005364
5365 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005366 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005367 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005368 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005369 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005370
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005371 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005372 QualType ResultTy;
5373 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5374 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5375 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005376 Matches.push_back(std::make_pair(I.getPair(),
5377 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005378 FoundNonTemplateFunction = true;
5379 }
Mike Stump11289f42009-09-09 15:08:12 +00005380 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005381 }
5382
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005383 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005384 if (Matches.empty()) {
5385 if (Complain) {
5386 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5387 << OvlExpr->getName() << FunctionType;
5388 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5389 E = OvlExpr->decls_end();
5390 I != E; ++I)
5391 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5392 NoteOverloadCandidate(F);
5393 }
5394
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005395 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005396 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005397 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005398 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005399 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005400 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005401 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005402 return Result;
5403 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005404
5405 // C++ [over.over]p4:
5406 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005407 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005408 // [...] and any given function template specialization F1 is
5409 // eliminated if the set contains a second function template
5410 // specialization whose function template is more specialized
5411 // than the function template of F1 according to the partial
5412 // ordering rules of 14.5.5.2.
5413
5414 // The algorithm specified above is quadratic. We instead use a
5415 // two-pass algorithm (similar to the one used to identify the
5416 // best viable function in an overload set) that identifies the
5417 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005418
5419 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5420 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5421 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005422
5423 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005424 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005425 TPOC_Other, From->getLocStart(),
5426 PDiag(),
5427 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005428 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005429 PDiag(diag::note_ovl_candidate)
5430 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005431 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005432 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005433 FoundResult = Matches[Result - MatchesCopy.begin()].first;
5434 if (Complain)
5435 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00005436 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005437 }
Mike Stump11289f42009-09-09 15:08:12 +00005438
Douglas Gregorfae1d712009-09-26 03:56:17 +00005439 // [...] any function template specializations in the set are
5440 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005441 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005442 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005443 ++I;
5444 else {
John McCalla0296f72010-03-19 07:35:19 +00005445 Matches[I] = Matches[--N];
5446 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005447 }
5448 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005449
Mike Stump11289f42009-09-09 15:08:12 +00005450 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005451 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005452 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005453 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005454 FoundResult = Matches[0].first;
John McCall58cc69d2010-01-27 01:50:18 +00005455 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00005456 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5457 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005458 }
Mike Stump11289f42009-09-09 15:08:12 +00005459
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005460 // FIXME: We should probably return the same thing that BestViableFunction
5461 // returns (even if we issue the diagnostics here).
5462 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005463 << Matches[0].second->getDeclName();
5464 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5465 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005466 return 0;
5467}
5468
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005469/// \brief Given an expression that refers to an overloaded function, try to
5470/// resolve that overloaded function expression down to a single function.
5471///
5472/// This routine can only resolve template-ids that refer to a single function
5473/// template, where that template-id refers to a single template whose template
5474/// arguments are either provided by the template-id or have defaults,
5475/// as described in C++0x [temp.arg.explicit]p3.
5476FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5477 // C++ [over.over]p1:
5478 // [...] [Note: any redundant set of parentheses surrounding the
5479 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005480 // C++ [over.over]p1:
5481 // [...] The overloaded function name can be preceded by the &
5482 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005483
5484 if (From->getType() != Context.OverloadTy)
5485 return 0;
5486
5487 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005488
5489 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005490 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005491 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005492
5493 TemplateArgumentListInfo ExplicitTemplateArgs;
5494 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005495
5496 // Look through all of the overloaded functions, searching for one
5497 // whose type matches exactly.
5498 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005499 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5500 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005501 // C++0x [temp.arg.explicit]p3:
5502 // [...] In contexts where deduction is done and fails, or in contexts
5503 // where deduction is not done, if a template argument list is
5504 // specified and it, along with any default template arguments,
5505 // identifies a single function template specialization, then the
5506 // template-id is an lvalue for the function template specialization.
5507 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5508
5509 // C++ [over.over]p2:
5510 // If the name is a function template, template argument deduction is
5511 // done (14.8.2.2), and if the argument deduction succeeds, the
5512 // resulting template argument list is used to generate a single
5513 // function template specialization, which is added to the set of
5514 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005515 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005516 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005517 if (TemplateDeductionResult Result
5518 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5519 Specialization, Info)) {
5520 // FIXME: make a note of the failed deduction for diagnostics.
5521 (void)Result;
5522 continue;
5523 }
5524
5525 // Multiple matches; we can't resolve to a single declaration.
5526 if (Matched)
5527 return 0;
5528
5529 Matched = Specialization;
5530 }
5531
5532 return Matched;
5533}
5534
Douglas Gregorcabea402009-09-22 15:41:20 +00005535/// \brief Add a single candidate to the overload set.
5536static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005537 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005538 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005539 Expr **Args, unsigned NumArgs,
5540 OverloadCandidateSet &CandidateSet,
5541 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005542 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005543 if (isa<UsingShadowDecl>(Callee))
5544 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5545
Douglas Gregorcabea402009-09-22 15:41:20 +00005546 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005547 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005548 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005549 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005550 return;
John McCalld14a8642009-11-21 08:51:07 +00005551 }
5552
5553 if (FunctionTemplateDecl *FuncTemplate
5554 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005555 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5556 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005557 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005558 return;
5559 }
5560
5561 assert(false && "unhandled case in overloaded call candidate");
5562
5563 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005564}
5565
5566/// \brief Add the overload candidates named by callee and/or found by argument
5567/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005568void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005569 Expr **Args, unsigned NumArgs,
5570 OverloadCandidateSet &CandidateSet,
5571 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005572
5573#ifndef NDEBUG
5574 // Verify that ArgumentDependentLookup is consistent with the rules
5575 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005576 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005577 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5578 // and let Y be the lookup set produced by argument dependent
5579 // lookup (defined as follows). If X contains
5580 //
5581 // -- a declaration of a class member, or
5582 //
5583 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005584 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005585 //
5586 // -- a declaration that is neither a function or a function
5587 // template
5588 //
5589 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005590
John McCall57500772009-12-16 12:17:52 +00005591 if (ULE->requiresADL()) {
5592 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5593 E = ULE->decls_end(); I != E; ++I) {
5594 assert(!(*I)->getDeclContext()->isRecord());
5595 assert(isa<UsingShadowDecl>(*I) ||
5596 !(*I)->getDeclContext()->isFunctionOrMethod());
5597 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005598 }
5599 }
5600#endif
5601
John McCall57500772009-12-16 12:17:52 +00005602 // It would be nice to avoid this copy.
5603 TemplateArgumentListInfo TABuffer;
5604 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5605 if (ULE->hasExplicitTemplateArgs()) {
5606 ULE->copyTemplateArgumentsInto(TABuffer);
5607 ExplicitTemplateArgs = &TABuffer;
5608 }
5609
5610 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5611 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005612 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005613 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005614 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005615
John McCall57500772009-12-16 12:17:52 +00005616 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005617 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5618 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005619 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005620 CandidateSet,
5621 PartialOverloading);
5622}
John McCalld681c392009-12-16 08:11:27 +00005623
John McCall57500772009-12-16 12:17:52 +00005624static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5625 Expr **Args, unsigned NumArgs) {
5626 Fn->Destroy(SemaRef.Context);
5627 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5628 Args[Arg]->Destroy(SemaRef.Context);
5629 return SemaRef.ExprError();
5630}
5631
John McCalld681c392009-12-16 08:11:27 +00005632/// Attempts to recover from a call where no functions were found.
5633///
5634/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005635static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005636BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005637 UnresolvedLookupExpr *ULE,
5638 SourceLocation LParenLoc,
5639 Expr **Args, unsigned NumArgs,
5640 SourceLocation *CommaLocs,
5641 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005642
5643 CXXScopeSpec SS;
5644 if (ULE->getQualifier()) {
5645 SS.setScopeRep(ULE->getQualifier());
5646 SS.setRange(ULE->getQualifierRange());
5647 }
5648
John McCall57500772009-12-16 12:17:52 +00005649 TemplateArgumentListInfo TABuffer;
5650 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5651 if (ULE->hasExplicitTemplateArgs()) {
5652 ULE->copyTemplateArgumentsInto(TABuffer);
5653 ExplicitTemplateArgs = &TABuffer;
5654 }
5655
John McCalld681c392009-12-16 08:11:27 +00005656 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5657 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005658 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005659 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005660
John McCall57500772009-12-16 12:17:52 +00005661 assert(!R.empty() && "lookup results empty despite recovery");
5662
5663 // Build an implicit member call if appropriate. Just drop the
5664 // casts and such from the call, we don't really care.
5665 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5666 if ((*R.begin())->isCXXClassMember())
5667 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5668 else if (ExplicitTemplateArgs)
5669 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5670 else
5671 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5672
5673 if (NewFn.isInvalid())
5674 return Destroy(SemaRef, Fn, Args, NumArgs);
5675
5676 Fn->Destroy(SemaRef.Context);
5677
5678 // This shouldn't cause an infinite loop because we're giving it
5679 // an expression with non-empty lookup results, which should never
5680 // end up here.
5681 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5682 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5683 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005684}
Douglas Gregorcabea402009-09-22 15:41:20 +00005685
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005686/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005687/// (which eventually refers to the declaration Func) and the call
5688/// arguments Args/NumArgs, attempt to resolve the function call down
5689/// to a specific function. If overload resolution succeeds, returns
5690/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005691/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005692/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005693Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005694Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005695 SourceLocation LParenLoc,
5696 Expr **Args, unsigned NumArgs,
5697 SourceLocation *CommaLocs,
5698 SourceLocation RParenLoc) {
5699#ifndef NDEBUG
5700 if (ULE->requiresADL()) {
5701 // To do ADL, we must have found an unqualified name.
5702 assert(!ULE->getQualifier() && "qualified name with ADL");
5703
5704 // We don't perform ADL for implicit declarations of builtins.
5705 // Verify that this was correctly set up.
5706 FunctionDecl *F;
5707 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5708 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5709 F->getBuiltinID() && F->isImplicit())
5710 assert(0 && "performing ADL for builtin");
5711
5712 // We don't perform ADL in C.
5713 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5714 }
5715#endif
5716
John McCallbc077cf2010-02-08 23:07:23 +00005717 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005718
John McCall57500772009-12-16 12:17:52 +00005719 // Add the functions denoted by the callee to the set of candidate
5720 // functions, including those from argument-dependent lookup.
5721 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005722
5723 // If we found nothing, try to recover.
5724 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5725 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005726 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005727 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00005728 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005729
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005730 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005731 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005732 case OR_Success: {
5733 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00005734 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall16df1e52010-03-30 21:47:33 +00005735 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00005736 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5737 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005738
5739 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005740 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005741 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005742 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005743 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005744 break;
5745
5746 case OR_Ambiguous:
5747 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005748 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005749 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005750 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005751
5752 case OR_Deleted:
5753 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5754 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005755 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005756 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005757 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005758 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005759 }
5760
5761 // Overload resolution failed. Destroy all of the subexpressions and
5762 // return NULL.
5763 Fn->Destroy(Context);
5764 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5765 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005766 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005767}
5768
John McCall4c4c1df2010-01-26 03:27:55 +00005769static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005770 return Functions.size() > 1 ||
5771 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5772}
5773
Douglas Gregor084d8552009-03-13 23:49:33 +00005774/// \brief Create a unary operation that may resolve to an overloaded
5775/// operator.
5776///
5777/// \param OpLoc The location of the operator itself (e.g., '*').
5778///
5779/// \param OpcIn The UnaryOperator::Opcode that describes this
5780/// operator.
5781///
5782/// \param Functions The set of non-member functions that will be
5783/// considered by overload resolution. The caller needs to build this
5784/// set based on the context using, e.g.,
5785/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5786/// set should not contain any member functions; those will be added
5787/// by CreateOverloadedUnaryOp().
5788///
5789/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005790Sema::OwningExprResult
5791Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5792 const UnresolvedSetImpl &Fns,
5793 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005794 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5795 Expr *Input = (Expr *)input.get();
5796
5797 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5798 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5799 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5800
5801 Expr *Args[2] = { Input, 0 };
5802 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005803
Douglas Gregor084d8552009-03-13 23:49:33 +00005804 // For post-increment and post-decrement, add the implicit '0' as
5805 // the second argument, so that we know this is a post-increment or
5806 // post-decrement.
5807 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5808 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005809 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005810 SourceLocation());
5811 NumArgs = 2;
5812 }
5813
5814 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005815 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005816 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005817 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005818 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005819 /*ADL*/ true, IsOverloaded(Fns));
5820 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005821
Douglas Gregor084d8552009-03-13 23:49:33 +00005822 input.release();
5823 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5824 &Args[0], NumArgs,
5825 Context.DependentTy,
5826 OpLoc));
5827 }
5828
5829 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005830 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005831
5832 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005833 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005834
5835 // Add operator candidates that are member functions.
5836 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5837
John McCall4c4c1df2010-01-26 03:27:55 +00005838 // Add candidates from ADL.
5839 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005840 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005841 /*ExplicitTemplateArgs*/ 0,
5842 CandidateSet);
5843
Douglas Gregor084d8552009-03-13 23:49:33 +00005844 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005845 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005846
5847 // Perform overload resolution.
5848 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005849 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005850 case OR_Success: {
5851 // We found a built-in operator or an overloaded operator.
5852 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005853
Douglas Gregor084d8552009-03-13 23:49:33 +00005854 if (FnDecl) {
5855 // We matched an overloaded operator. Build a call to that
5856 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005857
Douglas Gregor084d8552009-03-13 23:49:33 +00005858 // Convert the arguments.
5859 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00005860 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00005861
John McCall16df1e52010-03-30 21:47:33 +00005862 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5863 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005864 return ExprError();
5865 } else {
5866 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005867 OwningExprResult InputInit
5868 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005869 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005870 SourceLocation(),
5871 move(input));
5872 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005873 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005874
Douglas Gregore6600372009-12-23 17:40:29 +00005875 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005876 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005877 }
5878
5879 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005880 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005881
Douglas Gregor084d8552009-03-13 23:49:33 +00005882 // Build the actual expression node.
5883 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5884 SourceLocation());
5885 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005886
Douglas Gregor084d8552009-03-13 23:49:33 +00005887 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005888 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005889 ExprOwningPtr<CallExpr> TheCall(this,
5890 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005891 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005892
5893 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5894 FnDecl))
5895 return ExprError();
5896
5897 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005898 } else {
5899 // We matched a built-in operator. Convert the arguments, then
5900 // break out so that we will build the appropriate built-in
5901 // operator node.
5902 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005903 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005904 return ExprError();
5905
5906 break;
5907 }
5908 }
5909
5910 case OR_No_Viable_Function:
5911 // No viable function; fall through to handling this as a
5912 // built-in operator, which will produce an error message for us.
5913 break;
5914
5915 case OR_Ambiguous:
5916 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5917 << UnaryOperator::getOpcodeStr(Opc)
5918 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005919 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005920 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005921 return ExprError();
5922
5923 case OR_Deleted:
5924 Diag(OpLoc, diag::err_ovl_deleted_oper)
5925 << Best->Function->isDeleted()
5926 << UnaryOperator::getOpcodeStr(Opc)
5927 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005928 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005929 return ExprError();
5930 }
5931
5932 // Either we found no viable overloaded operator or we matched a
5933 // built-in operator. In either case, fall through to trying to
5934 // build a built-in operation.
5935 input.release();
5936 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5937}
5938
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005939/// \brief Create a binary operation that may resolve to an overloaded
5940/// operator.
5941///
5942/// \param OpLoc The location of the operator itself (e.g., '+').
5943///
5944/// \param OpcIn The BinaryOperator::Opcode that describes this
5945/// operator.
5946///
5947/// \param Functions The set of non-member functions that will be
5948/// considered by overload resolution. The caller needs to build this
5949/// set based on the context using, e.g.,
5950/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5951/// set should not contain any member functions; those will be added
5952/// by CreateOverloadedBinOp().
5953///
5954/// \param LHS Left-hand argument.
5955/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005956Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005957Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005958 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005959 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005960 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005961 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005962 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005963
5964 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5965 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5966 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5967
5968 // If either side is type-dependent, create an appropriate dependent
5969 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005970 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00005971 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005972 // If there are no functions to store, just build a dependent
5973 // BinaryOperator or CompoundAssignment.
5974 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5975 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5976 Context.DependentTy, OpLoc));
5977
5978 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5979 Context.DependentTy,
5980 Context.DependentTy,
5981 Context.DependentTy,
5982 OpLoc));
5983 }
John McCall4c4c1df2010-01-26 03:27:55 +00005984
5985 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00005986 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005987 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005988 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005989 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005990 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00005991
John McCall4c4c1df2010-01-26 03:27:55 +00005992 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005993 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005994 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005995 Context.DependentTy,
5996 OpLoc));
5997 }
5998
5999 // If this is the .* operator, which is not overloadable, just
6000 // create a built-in binary operator.
6001 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006002 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006003
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006004 // If this is the assignment operator, we only perform overload resolution
6005 // if the left-hand side is a class or enumeration type. This is actually
6006 // a hack. The standard requires that we do overload resolution between the
6007 // various built-in candidates, but as DR507 points out, this can lead to
6008 // problems. So we do it this way, which pretty much follows what GCC does.
6009 // Note that we go the traditional code path for compound assignment forms.
6010 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006011 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006012
Douglas Gregor084d8552009-03-13 23:49:33 +00006013 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006014 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006015
6016 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006017 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006018
6019 // Add operator candidates that are member functions.
6020 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6021
John McCall4c4c1df2010-01-26 03:27:55 +00006022 // Add candidates from ADL.
6023 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6024 Args, 2,
6025 /*ExplicitTemplateArgs*/ 0,
6026 CandidateSet);
6027
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006028 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006029 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006030
6031 // Perform overload resolution.
6032 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006033 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006034 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006035 // We found a built-in operator or an overloaded operator.
6036 FunctionDecl *FnDecl = Best->Function;
6037
6038 if (FnDecl) {
6039 // We matched an overloaded operator. Build a call to that
6040 // operator.
6041
6042 // Convert the arguments.
6043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006044 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006045 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006046
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006047 OwningExprResult Arg1
6048 = PerformCopyInitialization(
6049 InitializedEntity::InitializeParameter(
6050 FnDecl->getParamDecl(0)),
6051 SourceLocation(),
6052 Owned(Args[1]));
6053 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006054 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006055
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006056 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006057 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006058 return ExprError();
6059
6060 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006061 } else {
6062 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006063 OwningExprResult Arg0
6064 = PerformCopyInitialization(
6065 InitializedEntity::InitializeParameter(
6066 FnDecl->getParamDecl(0)),
6067 SourceLocation(),
6068 Owned(Args[0]));
6069 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006070 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006071
6072 OwningExprResult Arg1
6073 = PerformCopyInitialization(
6074 InitializedEntity::InitializeParameter(
6075 FnDecl->getParamDecl(1)),
6076 SourceLocation(),
6077 Owned(Args[1]));
6078 if (Arg1.isInvalid())
6079 return ExprError();
6080 Args[0] = LHS = Arg0.takeAs<Expr>();
6081 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006082 }
6083
6084 // Determine the result type
6085 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006086 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006087 ResultTy = ResultTy.getNonReferenceType();
6088
6089 // Build the actual expression node.
6090 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006091 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006092 UsualUnaryConversions(FnExpr);
6093
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006094 ExprOwningPtr<CXXOperatorCallExpr>
6095 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6096 Args, 2, ResultTy,
6097 OpLoc));
6098
6099 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6100 FnDecl))
6101 return ExprError();
6102
6103 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006104 } else {
6105 // We matched a built-in operator. Convert the arguments, then
6106 // break out so that we will build the appropriate built-in
6107 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006108 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006109 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006110 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006111 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006112 return ExprError();
6113
6114 break;
6115 }
6116 }
6117
Douglas Gregor66950a32009-09-30 21:46:01 +00006118 case OR_No_Viable_Function: {
6119 // C++ [over.match.oper]p9:
6120 // If the operator is the operator , [...] and there are no
6121 // viable functions, then the operator is assumed to be the
6122 // built-in operator and interpreted according to clause 5.
6123 if (Opc == BinaryOperator::Comma)
6124 break;
6125
Sebastian Redl027de2a2009-05-21 11:50:50 +00006126 // For class as left operand for assignment or compound assigment operator
6127 // do not fall through to handling in built-in, but report that no overloaded
6128 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006129 OwningExprResult Result = ExprError();
6130 if (Args[0]->getType()->isRecordType() &&
6131 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006132 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6133 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006134 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006135 } else {
6136 // No viable function; try to create a built-in operation, which will
6137 // produce an error. Then, show the non-viable candidates.
6138 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006139 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006140 assert(Result.isInvalid() &&
6141 "C++ binary operator overloading is missing candidates!");
6142 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006143 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006144 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006145 return move(Result);
6146 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006147
6148 case OR_Ambiguous:
6149 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6150 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006151 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006152 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006153 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006154 return ExprError();
6155
6156 case OR_Deleted:
6157 Diag(OpLoc, diag::err_ovl_deleted_oper)
6158 << Best->Function->isDeleted()
6159 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006160 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006161 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006162 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006163 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006164
Douglas Gregor66950a32009-09-30 21:46:01 +00006165 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006166 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006167}
6168
Sebastian Redladba46e2009-10-29 20:17:01 +00006169Action::OwningExprResult
6170Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6171 SourceLocation RLoc,
6172 ExprArg Base, ExprArg Idx) {
6173 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6174 static_cast<Expr*>(Idx.get()) };
6175 DeclarationName OpName =
6176 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6177
6178 // If either side is type-dependent, create an appropriate dependent
6179 // expression.
6180 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6181
John McCall58cc69d2010-01-27 01:50:18 +00006182 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006183 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006184 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006185 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006186 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006187 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006188
6189 Base.release();
6190 Idx.release();
6191 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6192 Args, 2,
6193 Context.DependentTy,
6194 RLoc));
6195 }
6196
6197 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006198 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006199
6200 // Subscript can only be overloaded as a member function.
6201
6202 // Add operator candidates that are member functions.
6203 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6204
6205 // Add builtin operator candidates.
6206 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6207
6208 // Perform overload resolution.
6209 OverloadCandidateSet::iterator Best;
6210 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6211 case OR_Success: {
6212 // We found a built-in operator or an overloaded operator.
6213 FunctionDecl *FnDecl = Best->Function;
6214
6215 if (FnDecl) {
6216 // We matched an overloaded operator. Build a call to that
6217 // operator.
6218
John McCalla0296f72010-03-19 07:35:19 +00006219 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +00006220
Sebastian Redladba46e2009-10-29 20:17:01 +00006221 // Convert the arguments.
6222 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006223 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006224 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006225 return ExprError();
6226
Anders Carlssona68e51e2010-01-29 18:37:50 +00006227 // Convert the arguments.
6228 OwningExprResult InputInit
6229 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6230 FnDecl->getParamDecl(0)),
6231 SourceLocation(),
6232 Owned(Args[1]));
6233 if (InputInit.isInvalid())
6234 return ExprError();
6235
6236 Args[1] = InputInit.takeAs<Expr>();
6237
Sebastian Redladba46e2009-10-29 20:17:01 +00006238 // Determine the result type
6239 QualType ResultTy
6240 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6241 ResultTy = ResultTy.getNonReferenceType();
6242
6243 // Build the actual expression node.
6244 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6245 LLoc);
6246 UsualUnaryConversions(FnExpr);
6247
6248 Base.release();
6249 Idx.release();
6250 ExprOwningPtr<CXXOperatorCallExpr>
6251 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6252 FnExpr, Args, 2,
6253 ResultTy, RLoc));
6254
6255 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6256 FnDecl))
6257 return ExprError();
6258
6259 return MaybeBindToTemporary(TheCall.release());
6260 } else {
6261 // We matched a built-in operator. Convert the arguments, then
6262 // break out so that we will build the appropriate built-in
6263 // operator node.
6264 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006265 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006266 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006267 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006268 return ExprError();
6269
6270 break;
6271 }
6272 }
6273
6274 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006275 if (CandidateSet.empty())
6276 Diag(LLoc, diag::err_ovl_no_oper)
6277 << Args[0]->getType() << /*subscript*/ 0
6278 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6279 else
6280 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6281 << Args[0]->getType()
6282 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006283 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006284 "[]", LLoc);
6285 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006286 }
6287
6288 case OR_Ambiguous:
6289 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6290 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006291 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006292 "[]", LLoc);
6293 return ExprError();
6294
6295 case OR_Deleted:
6296 Diag(LLoc, diag::err_ovl_deleted_oper)
6297 << Best->Function->isDeleted() << "[]"
6298 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006299 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006300 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006301 return ExprError();
6302 }
6303
6304 // We matched a built-in operator; build it.
6305 Base.release();
6306 Idx.release();
6307 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6308 Owned(Args[1]), RLoc);
6309}
6310
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006311/// BuildCallToMemberFunction - Build a call to a member
6312/// function. MemExpr is the expression that refers to the member
6313/// function (and includes the object parameter), Args/NumArgs are the
6314/// arguments to the function call (not including the object
6315/// parameter). The caller needs to validate that the member
6316/// expression refers to a member function or an overloaded member
6317/// function.
John McCall2d74de92009-12-01 22:10:20 +00006318Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006319Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6320 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006321 unsigned NumArgs, SourceLocation *CommaLocs,
6322 SourceLocation RParenLoc) {
6323 // Dig out the member expression. This holds both the object
6324 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006325 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6326
John McCall10eae182009-11-30 22:42:35 +00006327 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006328 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006329 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006330 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006331 if (isa<MemberExpr>(NakedMemExpr)) {
6332 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006333 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006334 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006335 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006336 } else {
6337 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006338 Qualifier = UnresExpr->getQualifier();
6339
John McCall6e9f8f62009-12-03 04:06:58 +00006340 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006341
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006342 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006343 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006344
John McCall2d74de92009-12-01 22:10:20 +00006345 // FIXME: avoid copy.
6346 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6347 if (UnresExpr->hasExplicitTemplateArgs()) {
6348 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6349 TemplateArgs = &TemplateArgsBuffer;
6350 }
6351
John McCall10eae182009-11-30 22:42:35 +00006352 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6353 E = UnresExpr->decls_end(); I != E; ++I) {
6354
John McCall6e9f8f62009-12-03 04:06:58 +00006355 NamedDecl *Func = *I;
6356 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6357 if (isa<UsingShadowDecl>(Func))
6358 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6359
John McCall10eae182009-11-30 22:42:35 +00006360 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006361 // If explicit template arguments were provided, we can't call a
6362 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006363 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006364 continue;
6365
John McCalla0296f72010-03-19 07:35:19 +00006366 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006367 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006368 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006369 } else {
John McCall10eae182009-11-30 22:42:35 +00006370 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006371 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006372 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006373 CandidateSet,
6374 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006375 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006376 }
Mike Stump11289f42009-09-09 15:08:12 +00006377
John McCall10eae182009-11-30 22:42:35 +00006378 DeclarationName DeclName = UnresExpr->getMemberName();
6379
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006380 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006381 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006382 case OR_Success:
6383 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006384 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006385 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006386 break;
6387
6388 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006389 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006390 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006391 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006392 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006393 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006394 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006395
6396 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006397 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006398 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006399 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006400 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006401 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006402
6403 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006404 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006405 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006406 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006407 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006408 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006409 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006410 }
6411
John McCall16df1e52010-03-30 21:47:33 +00006412 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006413
John McCall2d74de92009-12-01 22:10:20 +00006414 // If overload resolution picked a static member, build a
6415 // non-member call based on that function.
6416 if (Method->isStatic()) {
6417 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6418 Args, NumArgs, RParenLoc);
6419 }
6420
John McCall10eae182009-11-30 22:42:35 +00006421 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006422 }
6423
6424 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006425 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006426 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006427 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006428 Method->getResultType().getNonReferenceType(),
6429 RParenLoc));
6430
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006431 // Check for a valid return type.
6432 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6433 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006434 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006435
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006436 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006437 // We only need to do this if there was actually an overload; otherwise
6438 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006439 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006440 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006441 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6442 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006443 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006444 MemExpr->setBase(ObjectArg);
6445
6446 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006447 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006448 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006449 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006450 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006451
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006452 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006453 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006454
John McCall2d74de92009-12-01 22:10:20 +00006455 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006456}
6457
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006458/// BuildCallToObjectOfClassType - Build a call to an object of class
6459/// type (C++ [over.call.object]), which can end up invoking an
6460/// overloaded function call operator (@c operator()) or performing a
6461/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006462Sema::ExprResult
6463Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006464 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006465 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006466 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006467 SourceLocation RParenLoc) {
6468 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006469 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006470
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006471 // C++ [over.call.object]p1:
6472 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006473 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006474 // candidate functions includes at least the function call
6475 // operators of T. The function call operators of T are obtained by
6476 // ordinary lookup of the name operator() in the context of
6477 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006478 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006479 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006480
6481 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006482 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006483 << Object->getSourceRange()))
6484 return true;
6485
John McCall27b18f82009-11-17 02:14:36 +00006486 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6487 LookupQualifiedName(R, Record->getDecl());
6488 R.suppressDiagnostics();
6489
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006490 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006491 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006492 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006493 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006494 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006495 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006496
Douglas Gregorab7897a2008-11-19 22:57:39 +00006497 // C++ [over.call.object]p2:
6498 // In addition, for each conversion function declared in T of the
6499 // form
6500 //
6501 // operator conversion-type-id () cv-qualifier;
6502 //
6503 // where cv-qualifier is the same cv-qualification as, or a
6504 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006505 // denotes the type "pointer to function of (P1,...,Pn) returning
6506 // R", or the type "reference to pointer to function of
6507 // (P1,...,Pn) returning R", or the type "reference to function
6508 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006509 // is also considered as a candidate function. Similarly,
6510 // surrogate call functions are added to the set of candidate
6511 // functions for each conversion function declared in an
6512 // accessible base class provided the function is not hidden
6513 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006514 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006515 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006516 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006517 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006518 NamedDecl *D = *I;
6519 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6520 if (isa<UsingShadowDecl>(D))
6521 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6522
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006523 // Skip over templated conversion functions; they aren't
6524 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006525 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006526 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006527
John McCall6e9f8f62009-12-03 04:06:58 +00006528 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006529
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006530 // Strip the reference type (if any) and then the pointer type (if
6531 // any) to get down to what might be a function type.
6532 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6533 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6534 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006535
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006536 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006537 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006538 Object->getType(), Args, NumArgs,
6539 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006540 }
Mike Stump11289f42009-09-09 15:08:12 +00006541
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006542 // Perform overload resolution.
6543 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006544 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006545 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006546 // Overload resolution succeeded; we'll build the appropriate call
6547 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006548 break;
6549
6550 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006551 if (CandidateSet.empty())
6552 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6553 << Object->getType() << /*call*/ 1
6554 << Object->getSourceRange();
6555 else
6556 Diag(Object->getSourceRange().getBegin(),
6557 diag::err_ovl_no_viable_object_call)
6558 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006559 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006560 break;
6561
6562 case OR_Ambiguous:
6563 Diag(Object->getSourceRange().getBegin(),
6564 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006565 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006566 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006567 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006568
6569 case OR_Deleted:
6570 Diag(Object->getSourceRange().getBegin(),
6571 diag::err_ovl_deleted_object_call)
6572 << Best->Function->isDeleted()
6573 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006574 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006575 break;
Mike Stump11289f42009-09-09 15:08:12 +00006576 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006577
Douglas Gregorab7897a2008-11-19 22:57:39 +00006578 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006579 // We had an error; delete all of the subexpressions and return
6580 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006581 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006582 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006583 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006584 return true;
6585 }
6586
Douglas Gregorab7897a2008-11-19 22:57:39 +00006587 if (Best->Function == 0) {
6588 // Since there is no function declaration, this is one of the
6589 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006590 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006591 = cast<CXXConversionDecl>(
6592 Best->Conversions[0].UserDefined.ConversionFunction);
6593
John McCalla0296f72010-03-19 07:35:19 +00006594 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006595
Douglas Gregorab7897a2008-11-19 22:57:39 +00006596 // We selected one of the surrogate functions that converts the
6597 // object parameter to a function pointer. Perform the conversion
6598 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006599
6600 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006601 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006602 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6603 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006604
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006605 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006606 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006607 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006608 }
6609
John McCalla0296f72010-03-19 07:35:19 +00006610 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006611
Douglas Gregorab7897a2008-11-19 22:57:39 +00006612 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6613 // that calls this method, using Object for the implicit object
6614 // parameter and passing along the remaining arguments.
6615 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006616 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006617
6618 unsigned NumArgsInProto = Proto->getNumArgs();
6619 unsigned NumArgsToCheck = NumArgs;
6620
6621 // Build the full argument list for the method call (the
6622 // implicit object parameter is placed at the beginning of the
6623 // list).
6624 Expr **MethodArgs;
6625 if (NumArgs < NumArgsInProto) {
6626 NumArgsToCheck = NumArgsInProto;
6627 MethodArgs = new Expr*[NumArgsInProto + 1];
6628 } else {
6629 MethodArgs = new Expr*[NumArgs + 1];
6630 }
6631 MethodArgs[0] = Object;
6632 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6633 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006634
6635 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006636 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006637 UsualUnaryConversions(NewFn);
6638
6639 // Once we've built TheCall, all of the expressions are properly
6640 // owned.
6641 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006642 ExprOwningPtr<CXXOperatorCallExpr>
6643 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006644 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006645 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006646 delete [] MethodArgs;
6647
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006648 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6649 Method))
6650 return true;
6651
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006652 // We may have default arguments. If so, we need to allocate more
6653 // slots in the call for them.
6654 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006655 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006656 else if (NumArgs > NumArgsInProto)
6657 NumArgsToCheck = NumArgsInProto;
6658
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006659 bool IsError = false;
6660
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006661 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006662 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006663 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006664 TheCall->setArg(0, Object);
6665
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006666
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006667 // Check the argument types.
6668 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006669 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006670 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006671 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006672
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006673 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006674
6675 OwningExprResult InputInit
6676 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6677 Method->getParamDecl(i)),
6678 SourceLocation(), Owned(Arg));
6679
6680 IsError |= InputInit.isInvalid();
6681 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006682 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006683 OwningExprResult DefArg
6684 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6685 if (DefArg.isInvalid()) {
6686 IsError = true;
6687 break;
6688 }
6689
6690 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006691 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006692
6693 TheCall->setArg(i + 1, Arg);
6694 }
6695
6696 // If this is a variadic call, handle args passed through "...".
6697 if (Proto->isVariadic()) {
6698 // Promote the arguments (C99 6.5.2.2p7).
6699 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6700 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006701 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006702 TheCall->setArg(i + 1, Arg);
6703 }
6704 }
6705
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006706 if (IsError) return true;
6707
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006708 if (CheckFunctionCall(Method, TheCall.get()))
6709 return true;
6710
Douglas Gregore5e775b2010-04-13 15:50:39 +00006711 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006712}
6713
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006714/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006715/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006716/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006717Sema::OwningExprResult
6718Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6719 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006720 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006721
John McCallbc077cf2010-02-08 23:07:23 +00006722 SourceLocation Loc = Base->getExprLoc();
6723
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006724 // C++ [over.ref]p1:
6725 //
6726 // [...] An expression x->m is interpreted as (x.operator->())->m
6727 // for a class object x of type T if T::operator->() exists and if
6728 // the operator is selected as the best match function by the
6729 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006730 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006731 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006732 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006733
John McCallbc077cf2010-02-08 23:07:23 +00006734 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006735 PDiag(diag::err_typecheck_incomplete_tag)
6736 << Base->getSourceRange()))
6737 return ExprError();
6738
John McCall27b18f82009-11-17 02:14:36 +00006739 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6740 LookupQualifiedName(R, BaseRecord->getDecl());
6741 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006742
6743 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006744 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006745 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006746 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006747 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006748
6749 // Perform overload resolution.
6750 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006751 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006752 case OR_Success:
6753 // Overload resolution succeeded; we'll build the call below.
6754 break;
6755
6756 case OR_No_Viable_Function:
6757 if (CandidateSet.empty())
6758 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006759 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006760 else
6761 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006762 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006763 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006764 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006765
6766 case OR_Ambiguous:
6767 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006768 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006769 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006770 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006771
6772 case OR_Deleted:
6773 Diag(OpLoc, diag::err_ovl_deleted_oper)
6774 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006775 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006776 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006777 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006778 }
6779
John McCalla0296f72010-03-19 07:35:19 +00006780 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6781
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006782 // Convert the object parameter.
6783 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006784 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6785 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006786 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006787
6788 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006789 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006790
6791 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006792 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6793 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006794 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006795
6796 QualType ResultTy = Method->getResultType().getNonReferenceType();
6797 ExprOwningPtr<CXXOperatorCallExpr>
6798 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6799 &Base, 1, ResultTy, OpLoc));
6800
6801 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6802 Method))
6803 return ExprError();
6804 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006805}
6806
Douglas Gregorcd695e52008-11-10 20:40:00 +00006807/// FixOverloadedFunctionReference - E is an expression that refers to
6808/// a C++ overloaded function (possibly with some parentheses and
6809/// perhaps a '&' around it). We have resolved the overloaded function
6810/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006811/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00006812Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00006813 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006814 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006815 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6816 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006817 if (SubExpr == PE->getSubExpr())
6818 return PE->Retain();
6819
6820 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6821 }
6822
6823 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006824 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6825 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006826 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006827 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006828 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006829 if (SubExpr == ICE->getSubExpr())
6830 return ICE->Retain();
6831
6832 return new (Context) ImplicitCastExpr(ICE->getType(),
6833 ICE->getCastKind(),
6834 SubExpr,
6835 ICE->isLvalueCast());
6836 }
6837
6838 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006839 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006840 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006841 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6842 if (Method->isStatic()) {
6843 // Do nothing: static member functions aren't any different
6844 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006845 } else {
John McCalle66edc12009-11-24 19:00:30 +00006846 // Fix the sub expression, which really has to be an
6847 // UnresolvedLookupExpr holding an overloaded member function
6848 // or template.
John McCall16df1e52010-03-30 21:47:33 +00006849 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6850 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00006851 if (SubExpr == UnOp->getSubExpr())
6852 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006853
John McCalld14a8642009-11-21 08:51:07 +00006854 assert(isa<DeclRefExpr>(SubExpr)
6855 && "fixed to something other than a decl ref");
6856 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6857 && "fixed to a member ref with no nested name qualifier");
6858
6859 // We have taken the address of a pointer to member
6860 // function. Perform the computation here so that we get the
6861 // appropriate pointer to member type.
6862 QualType ClassType
6863 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6864 QualType MemPtrType
6865 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6866
6867 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6868 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006869 }
6870 }
John McCall16df1e52010-03-30 21:47:33 +00006871 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6872 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006873 if (SubExpr == UnOp->getSubExpr())
6874 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006875
Douglas Gregor51c538b2009-11-20 19:42:02 +00006876 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6877 Context.getPointerType(SubExpr->getType()),
6878 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006879 }
John McCalld14a8642009-11-21 08:51:07 +00006880
6881 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006882 // FIXME: avoid copy.
6883 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006884 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006885 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6886 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006887 }
6888
John McCalld14a8642009-11-21 08:51:07 +00006889 return DeclRefExpr::Create(Context,
6890 ULE->getQualifier(),
6891 ULE->getQualifierRange(),
6892 Fn,
6893 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006894 Fn->getType(),
6895 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006896 }
6897
John McCall10eae182009-11-30 22:42:35 +00006898 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006899 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006900 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6901 if (MemExpr->hasExplicitTemplateArgs()) {
6902 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6903 TemplateArgs = &TemplateArgsBuffer;
6904 }
John McCall6b51f282009-11-23 01:53:49 +00006905
John McCall2d74de92009-12-01 22:10:20 +00006906 Expr *Base;
6907
6908 // If we're filling in
6909 if (MemExpr->isImplicitAccess()) {
6910 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6911 return DeclRefExpr::Create(Context,
6912 MemExpr->getQualifier(),
6913 MemExpr->getQualifierRange(),
6914 Fn,
6915 MemExpr->getMemberLoc(),
6916 Fn->getType(),
6917 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006918 } else {
6919 SourceLocation Loc = MemExpr->getMemberLoc();
6920 if (MemExpr->getQualifier())
6921 Loc = MemExpr->getQualifierRange().getBegin();
6922 Base = new (Context) CXXThisExpr(Loc,
6923 MemExpr->getBaseType(),
6924 /*isImplicit=*/true);
6925 }
John McCall2d74de92009-12-01 22:10:20 +00006926 } else
6927 Base = MemExpr->getBase()->Retain();
6928
6929 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006930 MemExpr->isArrow(),
6931 MemExpr->getQualifier(),
6932 MemExpr->getQualifierRange(),
6933 Fn,
John McCall16df1e52010-03-30 21:47:33 +00006934 Found,
John McCall6b51f282009-11-23 01:53:49 +00006935 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006936 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006937 Fn->getType());
6938 }
6939
Douglas Gregor51c538b2009-11-20 19:42:02 +00006940 assert(false && "Invalid reference to overloaded function");
6941 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006942}
6943
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006944Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00006945 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006946 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00006947 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006948}
6949
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006950} // end namespace clang