blob: 6f7063b98f361cf8f3a9711e19e62d5744052f1d [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000229 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 break;
John McCall0d1da222010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000254 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261}
262
John McCall0d1da222010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000278namespace {
279 // Structure used by OverloadCandidate::DeductionFailureInfo to store
280 // template parameter and template argument information.
281 struct DFIParamWithArguments {
282 TemplateParameter Param;
283 TemplateArgument FirstArg;
284 TemplateArgument SecondArg;
285 };
286}
287
288/// \brief Convert from Sema's representation of template deduction information
289/// to the form used in overload-candidate information.
290OverloadCandidate::DeductionFailureInfo
291static MakeDeductionFailureInfo(Sema::TemplateDeductionResult TDK,
292 const Sema::TemplateDeductionInfo &Info) {
293 OverloadCandidate::DeductionFailureInfo Result;
294 Result.Result = static_cast<unsigned>(TDK);
295 Result.Data = 0;
296 switch (TDK) {
297 case Sema::TDK_Success:
298 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000299 case Sema::TDK_TooManyArguments:
300 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000301 break;
302
303 case Sema::TDK_Incomplete:
304 Result.Data = Info.Param.getOpaqueValue();
305 break;
306
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000307 case Sema::TDK_Inconsistent:
308 case Sema::TDK_InconsistentQuals: {
309 DFIParamWithArguments *Saved = new DFIParamWithArguments;
310 Saved->Param = Info.Param;
311 Saved->FirstArg = Info.FirstArg;
312 Saved->SecondArg = Info.SecondArg;
313 Result.Data = Saved;
314 break;
315 }
316
317 case Sema::TDK_SubstitutionFailure:
318 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000319 case Sema::TDK_InvalidExplicitArguments:
320 case Sema::TDK_FailedOverloadResolution:
321 break;
322 }
323
324 return Result;
325}
John McCall0d1da222010-01-12 00:44:57 +0000326
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000327void OverloadCandidate::DeductionFailureInfo::Destroy() {
328 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
329 case Sema::TDK_Success:
330 case Sema::TDK_InstantiationDepth:
331 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000332 case Sema::TDK_TooManyArguments:
333 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000334 break;
335
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000336 case Sema::TDK_Inconsistent:
337 case Sema::TDK_InconsistentQuals:
338 delete static_cast<DFIParamWithArguments*>(Data);
339 Data = 0;
340 break;
341
Douglas Gregor461761d2010-05-08 18:20:53 +0000342 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000343 case Sema::TDK_SubstitutionFailure:
344 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000345 case Sema::TDK_InvalidExplicitArguments:
346 case Sema::TDK_FailedOverloadResolution:
347 break;
348 }
349}
350
351TemplateParameter
352OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
353 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
354 case Sema::TDK_Success:
355 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000356 case Sema::TDK_TooManyArguments:
357 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000358 return TemplateParameter();
359
360 case Sema::TDK_Incomplete:
361 return TemplateParameter::getFromOpaqueValue(Data);
362
363 case Sema::TDK_Inconsistent:
364 case Sema::TDK_InconsistentQuals:
365 return static_cast<DFIParamWithArguments*>(Data)->Param;
366
367 // Unhandled
368 case Sema::TDK_SubstitutionFailure:
369 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370 case Sema::TDK_InvalidExplicitArguments:
371 case Sema::TDK_FailedOverloadResolution:
372 break;
373 }
374
375 return TemplateParameter();
376}
377
378const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
379 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
380 case Sema::TDK_Success:
381 case Sema::TDK_InstantiationDepth:
382 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000383 case Sema::TDK_TooManyArguments:
384 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 return 0;
386
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000387 case Sema::TDK_Inconsistent:
388 case Sema::TDK_InconsistentQuals:
389 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
390
Douglas Gregor461761d2010-05-08 18:20:53 +0000391 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000392 case Sema::TDK_SubstitutionFailure:
393 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000394 case Sema::TDK_InvalidExplicitArguments:
395 case Sema::TDK_FailedOverloadResolution:
396 break;
397 }
398
399 return 0;
400}
401
402const TemplateArgument *
403OverloadCandidate::DeductionFailureInfo::getSecondArg() {
404 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
405 case Sema::TDK_Success:
406 case Sema::TDK_InstantiationDepth:
407 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000408 case Sema::TDK_TooManyArguments:
409 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000410 return 0;
411
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000412 case Sema::TDK_Inconsistent:
413 case Sema::TDK_InconsistentQuals:
414 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
415
Douglas Gregor461761d2010-05-08 18:20:53 +0000416 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000417 case Sema::TDK_SubstitutionFailure:
418 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000419 case Sema::TDK_InvalidExplicitArguments:
420 case Sema::TDK_FailedOverloadResolution:
421 break;
422 }
423
424 return 0;
425}
426
427void OverloadCandidateSet::clear() {
428 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
429 if (C->FailureKind == ovl_fail_bad_deduction)
430 C->DeductionFailure.Destroy();
431 }
432
433 inherited::clear();
434 Functions.clear();
435}
436
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000437// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000438// overload of the declarations in Old. This routine returns false if
439// New and Old cannot be overloaded, e.g., if New has the same
440// signature as some function in Old (C++ 1.3.10) or if the Old
441// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000442// it does return false, MatchedDecl will point to the decl that New
443// cannot be overloaded with. This decl may be a UsingShadowDecl on
444// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000445//
446// Example: Given the following input:
447//
448// void f(int, float); // #1
449// void f(int, int); // #2
450// int f(int, int); // #3
451//
452// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000453// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000454//
John McCall3d988d92009-12-02 08:47:38 +0000455// When we process #2, Old contains only the FunctionDecl for #1. By
456// comparing the parameter types, we see that #1 and #2 are overloaded
457// (since they have different signatures), so this routine returns
458// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000459//
John McCall3d988d92009-12-02 08:47:38 +0000460// When we process #3, Old is an overload set containing #1 and #2. We
461// compare the signatures of #3 to #1 (they're overloaded, so we do
462// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
463// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000464// signature), IsOverload returns false and MatchedDecl will be set to
465// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000466Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000467Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
468 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000469 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000470 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000471 NamedDecl *OldD = (*I)->getUnderlyingDecl();
472 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000473 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000474 Match = *I;
475 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476 }
John McCall3d988d92009-12-02 08:47:38 +0000477 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000478 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000479 Match = *I;
480 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000481 }
John McCall84d87672009-12-10 09:41:52 +0000482 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
483 // We can overload with these, which can show up when doing
484 // redeclaration checks for UsingDecls.
485 assert(Old.getLookupKind() == LookupUsingDeclName);
486 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
487 // Optimistically assume that an unresolved using decl will
488 // overload; if it doesn't, we'll have to diagnose during
489 // template instantiation.
490 } else {
John McCall1f82f242009-11-18 22:49:29 +0000491 // (C++ 13p1):
492 // Only function declarations can be overloaded; object and type
493 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000494 Match = *I;
495 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000496 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 }
John McCall1f82f242009-11-18 22:49:29 +0000498
John McCalldaa3d6b2009-12-09 03:35:25 +0000499 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000500}
501
502bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
503 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
504 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
505
506 // C++ [temp.fct]p2:
507 // A function template can be overloaded with other function templates
508 // and with normal (non-template) functions.
509 if ((OldTemplate == 0) != (NewTemplate == 0))
510 return true;
511
512 // Is the function New an overload of the function Old?
513 QualType OldQType = Context.getCanonicalType(Old->getType());
514 QualType NewQType = Context.getCanonicalType(New->getType());
515
516 // Compare the signatures (C++ 1.3.10) of the two functions to
517 // determine whether they are overloads. If we find any mismatch
518 // in the signature, they are overloads.
519
520 // If either of these functions is a K&R-style function (no
521 // prototype), then we consider them to have matching signatures.
522 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
523 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
524 return false;
525
526 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
527 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
528
529 // The signature of a function includes the types of its
530 // parameters (C++ 1.3.10), which includes the presence or absence
531 // of the ellipsis; see C++ DR 357).
532 if (OldQType != NewQType &&
533 (OldType->getNumArgs() != NewType->getNumArgs() ||
534 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000535 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000536 return true;
537
538 // C++ [temp.over.link]p4:
539 // The signature of a function template consists of its function
540 // signature, its return type and its template parameter list. The names
541 // of the template parameters are significant only for establishing the
542 // relationship between the template parameters and the rest of the
543 // signature.
544 //
545 // We check the return type and template parameter lists for function
546 // templates first; the remaining checks follow.
547 if (NewTemplate &&
548 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
549 OldTemplate->getTemplateParameters(),
550 false, TPL_TemplateMatch) ||
551 OldType->getResultType() != NewType->getResultType()))
552 return true;
553
554 // If the function is a class member, its signature includes the
555 // cv-qualifiers (if any) on the function itself.
556 //
557 // As part of this, also check whether one of the member functions
558 // is static, in which case they are not overloads (C++
559 // 13.1p2). While not part of the definition of the signature,
560 // this check is important to determine whether these functions
561 // can be overloaded.
562 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
563 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
564 if (OldMethod && NewMethod &&
565 !OldMethod->isStatic() && !NewMethod->isStatic() &&
566 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
567 return true;
568
569 // The signatures match; this is not an overload.
570 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000571}
572
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000573/// TryImplicitConversion - Attempt to perform an implicit conversion
574/// from the given expression (Expr) to the given type (ToType). This
575/// function returns an implicit conversion sequence that can be used
576/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000577///
578/// void f(float f);
579/// void g(int i) { f(i); }
580///
581/// this routine would produce an implicit conversion sequence to
582/// describe the initialization of f from i, which will be a standard
583/// conversion sequence containing an lvalue-to-rvalue conversion (C++
584/// 4.1) followed by a floating-integral conversion (C++ 4.9).
585//
586/// Note that this routine only determines how the conversion can be
587/// performed; it does not actually perform the conversion. As such,
588/// it will not produce any diagnostics if no conversion is available,
589/// but will instead return an implicit conversion sequence of kind
590/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000591///
592/// If @p SuppressUserConversions, then user-defined conversions are
593/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000594/// If @p AllowExplicit, then explicit user-defined conversions are
595/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000596ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000597Sema::TryImplicitConversion(Expr* From, QualType ToType,
598 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000599 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000600 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000601 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000602 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000603 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000604 return ICS;
605 }
606
607 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000608 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000609 return ICS;
610 }
611
Douglas Gregor5ab11652010-04-17 22:01:05 +0000612 if (SuppressUserConversions) {
613 // C++ [over.ics.user]p4:
614 // A conversion of an expression of class type to the same class
615 // type is given Exact Match rank, and a conversion of an
616 // expression of class type to a base class of that type is
617 // given Conversion rank, in spite of the fact that a copy/move
618 // constructor (i.e., a user-defined conversion function) is
619 // called for those cases.
620 QualType FromType = From->getType();
621 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
622 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
623 IsDerivedFrom(FromType, ToType))) {
624 // We're not in the case above, so there is no conversion that
625 // we can perform.
626 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
627 return ICS;
628 }
629
630 ICS.setStandard();
631 ICS.Standard.setAsIdentityConversion();
632 ICS.Standard.setFromType(FromType);
633 ICS.Standard.setAllToTypes(ToType);
634
635 // We don't actually check at this point whether there is a valid
636 // copy/move constructor, since overloading just assumes that it
637 // exists. When we actually perform initialization, we'll find the
638 // appropriate constructor to copy the returned object, if needed.
639 ICS.Standard.CopyConstructor = 0;
640
641 // Determine whether this is considered a derived-to-base conversion.
642 if (!Context.hasSameUnqualifiedType(FromType, ToType))
643 ICS.Standard.Second = ICK_Derived_To_Base;
644
645 return ICS;
646 }
647
648 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000649 OverloadCandidateSet Conversions(From->getExprLoc());
650 OverloadingResult UserDefResult
651 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000652 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000653
654 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000655 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000656 // C++ [over.ics.user]p4:
657 // A conversion of an expression of class type to the same class
658 // type is given Exact Match rank, and a conversion of an
659 // expression of class type to a base class of that type is
660 // given Conversion rank, in spite of the fact that a copy
661 // constructor (i.e., a user-defined conversion function) is
662 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000663 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000664 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000665 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000666 = Context.getCanonicalType(From->getType().getUnqualifiedType());
667 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000668 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000669 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000670 // Turn this into a "standard" conversion sequence, so that it
671 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000672 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000673 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000674 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000675 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000676 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000677 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000678 ICS.Standard.Second = ICK_Derived_To_Base;
679 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000680 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000681
682 // C++ [over.best.ics]p4:
683 // However, when considering the argument of a user-defined
684 // conversion function that is a candidate by 13.3.1.3 when
685 // invoked for the copying of the temporary in the second step
686 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
687 // 13.3.1.6 in all cases, only standard conversion sequences and
688 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000689 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000690 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000691 }
John McCalle8c8cd22010-01-13 22:30:33 +0000692 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000693 ICS.setAmbiguous();
694 ICS.Ambiguous.setFromType(From->getType());
695 ICS.Ambiguous.setToType(ToType);
696 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
697 Cand != Conversions.end(); ++Cand)
698 if (Cand->Viable)
699 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000700 } else {
John McCall65eb8792010-02-25 01:37:24 +0000701 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000702 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000703
704 return ICS;
705}
706
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000707/// PerformImplicitConversion - Perform an implicit conversion of the
708/// expression From to the type ToType. Returns true if there was an
709/// error, false otherwise. The expression From is replaced with the
710/// converted expression. Flavor is the kind of conversion we're
711/// performing, used in the error message. If @p AllowExplicit,
712/// explicit user-defined conversions are permitted.
713bool
714Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
715 AssignmentAction Action, bool AllowExplicit) {
716 ImplicitConversionSequence ICS;
717 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
718}
719
720bool
721Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
722 AssignmentAction Action, bool AllowExplicit,
723 ImplicitConversionSequence& ICS) {
724 ICS = TryImplicitConversion(From, ToType,
725 /*SuppressUserConversions=*/false,
726 AllowExplicit,
727 /*InOverloadResolution=*/false);
728 return PerformImplicitConversion(From, ToType, ICS, Action);
729}
730
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000731/// \brief Determine whether the conversion from FromType to ToType is a valid
732/// conversion that strips "noreturn" off the nested function type.
733static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
734 QualType ToType, QualType &ResultTy) {
735 if (Context.hasSameUnqualifiedType(FromType, ToType))
736 return false;
737
738 // Strip the noreturn off the type we're converting from; noreturn can
739 // safely be removed.
740 FromType = Context.getNoReturnType(FromType, false);
741 if (!Context.hasSameUnqualifiedType(FromType, ToType))
742 return false;
743
744 ResultTy = FromType;
745 return true;
746}
747
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000748/// IsStandardConversion - Determines whether there is a standard
749/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
750/// expression From to the type ToType. Standard conversion sequences
751/// only consider non-class types; for conversions that involve class
752/// types, use TryImplicitConversion. If a conversion exists, SCS will
753/// contain the standard conversion sequence required to perform this
754/// conversion and this routine will return true. Otherwise, this
755/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000756bool
757Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000758 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000759 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000760 QualType FromType = From->getType();
761
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000762 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000763 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000764 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000765 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000766 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000767 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000768
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000769 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000770 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000771 if (FromType->isRecordType() || ToType->isRecordType()) {
772 if (getLangOptions().CPlusPlus)
773 return false;
774
Mike Stump11289f42009-09-09 15:08:12 +0000775 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000776 }
777
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000778 // The first conversion can be an lvalue-to-rvalue conversion,
779 // array-to-pointer conversion, or function-to-pointer conversion
780 // (C++ 4p1).
781
Douglas Gregor980fb162010-04-29 18:24:40 +0000782 if (FromType == Context.OverloadTy) {
783 DeclAccessPair AccessPair;
784 if (FunctionDecl *Fn
785 = ResolveAddressOfOverloadedFunction(From, ToType, false,
786 AccessPair)) {
787 // We were able to resolve the address of the overloaded function,
788 // so we can convert to the type of that function.
789 FromType = Fn->getType();
790 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
791 if (!Method->isStatic()) {
792 Type *ClassType
793 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
794 FromType = Context.getMemberPointerType(FromType, ClassType);
795 }
796 }
797
798 // If the "from" expression takes the address of the overloaded
799 // function, update the type of the resulting expression accordingly.
800 if (FromType->getAs<FunctionType>())
801 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
802 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
803 FromType = Context.getPointerType(FromType);
804
805 // Check that we've computed the proper type after overload resolution.
806 assert(Context.hasSameType(FromType,
807 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
808 } else {
809 return false;
810 }
811 }
Mike Stump11289f42009-09-09 15:08:12 +0000812 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000813 // An lvalue (3.10) of a non-function, non-array type T can be
814 // converted to an rvalue.
815 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000816 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000817 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000818 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000819 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000820
821 // If T is a non-class type, the type of the rvalue is the
822 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000823 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
824 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000825 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000826 } else if (FromType->isArrayType()) {
827 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000828 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000829
830 // An lvalue or rvalue of type "array of N T" or "array of unknown
831 // bound of T" can be converted to an rvalue of type "pointer to
832 // T" (C++ 4.2p1).
833 FromType = Context.getArrayDecayedType(FromType);
834
835 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
836 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000837 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000838
839 // For the purpose of ranking in overload resolution
840 // (13.3.3.1.1), this conversion is considered an
841 // array-to-pointer conversion followed by a qualification
842 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000843 SCS.Second = ICK_Identity;
844 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000845 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000846 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000848 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
849 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000850 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000851
852 // An lvalue of function type T can be converted to an rvalue of
853 // type "pointer to T." The result is a pointer to the
854 // function. (C++ 4.3p1).
855 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000856 } else {
857 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000858 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000859 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000860 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000861
862 // The second conversion can be an integral promotion, floating
863 // point promotion, integral conversion, floating point conversion,
864 // floating-integral conversion, pointer conversion,
865 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000866 // For overloading in C, this can also be a "compatible-type"
867 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000868 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000869 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000870 // The unqualified versions of the types are the same: there's no
871 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000872 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000873 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000874 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000875 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000876 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000877 } else if (IsFloatingPointPromotion(FromType, ToType)) {
878 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000879 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000881 } else if (IsComplexPromotion(FromType, ToType)) {
882 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000883 SCS.Second = ICK_Complex_Promotion;
884 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000885 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000886 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000887 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000888 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000890 } else if (FromType->isComplexType() && ToType->isComplexType()) {
891 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000892 SCS.Second = ICK_Complex_Conversion;
893 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000894 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
895 (ToType->isComplexType() && FromType->isArithmeticType())) {
896 // Complex-real conversions (C99 6.3.1.7)
897 SCS.Second = ICK_Complex_Real;
898 FromType = ToType.getUnqualifiedType();
899 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
900 // Floating point conversions (C++ 4.8).
901 SCS.Second = ICK_Floating_Conversion;
902 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000903 } else if ((FromType->isFloatingType() &&
904 ToType->isIntegralType() && (!ToType->isBooleanType() &&
905 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000906 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000907 ToType->isFloatingType())) {
908 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000909 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000910 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000911 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
912 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000913 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000914 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000915 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000916 } else if (IsMemberPointerConversion(From, FromType, ToType,
917 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000918 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000919 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000920 } else if (ToType->isBooleanType() &&
921 (FromType->isArithmeticType() ||
922 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000923 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000924 FromType->isBlockPointerType() ||
925 FromType->isMemberPointerType() ||
926 FromType->isNullPtrType())) {
927 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000928 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000929 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000930 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000931 Context.typesAreCompatible(ToType, FromType)) {
932 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000933 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000934 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
935 // Treat a conversion that strips "noreturn" as an identity conversion.
936 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000937 } else {
938 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000939 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000940 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000941 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000943 QualType CanonFrom;
944 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000945 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000946 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000947 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000948 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000949 CanonFrom = Context.getCanonicalType(FromType);
950 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951 } else {
952 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000953 SCS.Third = ICK_Identity;
954
Mike Stump11289f42009-09-09 15:08:12 +0000955 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000956 // [...] Any difference in top-level cv-qualification is
957 // subsumed by the initialization itself and does not constitute
958 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000959 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000960 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000961 if (CanonFrom.getLocalUnqualifiedType()
962 == CanonTo.getLocalUnqualifiedType() &&
963 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000964 FromType = ToType;
965 CanonFrom = CanonTo;
966 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000967 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000968 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969
970 // If we have not converted the argument type to the parameter type,
971 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000972 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000973 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000975 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000976}
977
978/// IsIntegralPromotion - Determines whether the conversion from the
979/// expression From (whose potentially-adjusted type is FromType) to
980/// ToType is an integral promotion (C++ 4.5). If so, returns true and
981/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000982bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000983 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000984 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000985 if (!To) {
986 return false;
987 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000988
989 // An rvalue of type char, signed char, unsigned char, short int, or
990 // unsigned short int can be converted to an rvalue of type int if
991 // int can represent all the values of the source type; otherwise,
992 // the source rvalue can be converted to an rvalue of type unsigned
993 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000994 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
995 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000996 if (// We can promote any signed, promotable integer type to an int
997 (FromType->isSignedIntegerType() ||
998 // We can promote any unsigned integer type whose size is
999 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001000 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001001 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001002 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001003 }
1004
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001005 return To->getKind() == BuiltinType::UInt;
1006 }
1007
1008 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1009 // can be converted to an rvalue of the first of the following types
1010 // that can represent all the values of its underlying type: int,
1011 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001012
1013 // We pre-calculate the promotion type for enum types.
1014 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1015 if (ToType->isIntegerType())
1016 return Context.hasSameUnqualifiedType(ToType,
1017 FromEnumType->getDecl()->getPromotionType());
1018
1019 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001020 // Determine whether the type we're converting from is signed or
1021 // unsigned.
1022 bool FromIsSigned;
1023 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001024
1025 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1026 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027
1028 // The types we'll try to promote to, in the appropriate
1029 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001030 QualType PromoteTypes[6] = {
1031 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001032 Context.LongTy, Context.UnsignedLongTy ,
1033 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001034 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001035 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001036 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1037 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001038 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001039 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1040 // We found the type that we can promote to. If this is the
1041 // type we wanted, we have a promotion. Otherwise, no
1042 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001043 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001044 }
1045 }
1046 }
1047
1048 // An rvalue for an integral bit-field (9.6) can be converted to an
1049 // rvalue of type int if int can represent all the values of the
1050 // bit-field; otherwise, it can be converted to unsigned int if
1051 // unsigned int can represent all the values of the bit-field. If
1052 // the bit-field is larger yet, no integral promotion applies to
1053 // it. If the bit-field has an enumerated type, it is treated as any
1054 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001055 // FIXME: We should delay checking of bit-fields until we actually perform the
1056 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001057 using llvm::APSInt;
1058 if (From)
1059 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001060 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +00001061 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
1062 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1063 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1064 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001065
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001066 // Are we promoting to an int from a bitfield that fits in an int?
1067 if (BitWidth < ToSize ||
1068 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1069 return To->getKind() == BuiltinType::Int;
1070 }
Mike Stump11289f42009-09-09 15:08:12 +00001071
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001072 // Are we promoting to an unsigned int from an unsigned bitfield
1073 // that fits into an unsigned int?
1074 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1075 return To->getKind() == BuiltinType::UInt;
1076 }
Mike Stump11289f42009-09-09 15:08:12 +00001077
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001078 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001079 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001082 // An rvalue of type bool can be converted to an rvalue of type int,
1083 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001084 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001085 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001086 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087
1088 return false;
1089}
1090
1091/// IsFloatingPointPromotion - Determines whether the conversion from
1092/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1093/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001094bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001095 /// An rvalue of type float can be converted to an rvalue of type
1096 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001097 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1098 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001099 if (FromBuiltin->getKind() == BuiltinType::Float &&
1100 ToBuiltin->getKind() == BuiltinType::Double)
1101 return true;
1102
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001103 // C99 6.3.1.5p1:
1104 // When a float is promoted to double or long double, or a
1105 // double is promoted to long double [...].
1106 if (!getLangOptions().CPlusPlus &&
1107 (FromBuiltin->getKind() == BuiltinType::Float ||
1108 FromBuiltin->getKind() == BuiltinType::Double) &&
1109 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1110 return true;
1111 }
1112
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001113 return false;
1114}
1115
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001116/// \brief Determine if a conversion is a complex promotion.
1117///
1118/// A complex promotion is defined as a complex -> complex conversion
1119/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001120/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001121bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001122 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001123 if (!FromComplex)
1124 return false;
1125
John McCall9dd450b2009-09-21 23:43:11 +00001126 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001127 if (!ToComplex)
1128 return false;
1129
1130 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001131 ToComplex->getElementType()) ||
1132 IsIntegralPromotion(0, FromComplex->getElementType(),
1133 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001134}
1135
Douglas Gregor237f96c2008-11-26 23:31:11 +00001136/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1137/// the pointer type FromPtr to a pointer to type ToPointee, with the
1138/// same type qualifiers as FromPtr has on its pointee type. ToType,
1139/// if non-empty, will be a pointer to ToType that may or may not have
1140/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001141static QualType
1142BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001143 QualType ToPointee, QualType ToType,
1144 ASTContext &Context) {
1145 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1146 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001147 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001148
1149 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001150 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001151 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001152 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +00001153 return ToType;
1154
1155 // Build a pointer to ToPointee. It has the right qualifiers
1156 // already.
1157 return Context.getPointerType(ToPointee);
1158 }
1159
1160 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001161 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001162 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1163 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001164}
1165
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001166/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1167/// the FromType, which is an objective-c pointer, to ToType, which may or may
1168/// not have the right set of qualifiers.
1169static QualType
1170BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1171 QualType ToType,
1172 ASTContext &Context) {
1173 QualType CanonFromType = Context.getCanonicalType(FromType);
1174 QualType CanonToType = Context.getCanonicalType(ToType);
1175 Qualifiers Quals = CanonFromType.getQualifiers();
1176
1177 // Exact qualifier match -> return the pointer type we're converting to.
1178 if (CanonToType.getLocalQualifiers() == Quals)
1179 return ToType;
1180
1181 // Just build a canonical type that has the right qualifiers.
1182 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1183}
1184
Mike Stump11289f42009-09-09 15:08:12 +00001185static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001186 bool InOverloadResolution,
1187 ASTContext &Context) {
1188 // Handle value-dependent integral null pointer constants correctly.
1189 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1190 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1191 Expr->getType()->isIntegralType())
1192 return !InOverloadResolution;
1193
Douglas Gregor56751b52009-09-25 04:25:58 +00001194 return Expr->isNullPointerConstant(Context,
1195 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1196 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001197}
Mike Stump11289f42009-09-09 15:08:12 +00001198
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001199/// IsPointerConversion - Determines whether the conversion of the
1200/// expression From, which has the (possibly adjusted) type FromType,
1201/// can be converted to the type ToType via a pointer conversion (C++
1202/// 4.10). If so, returns true and places the converted type (that
1203/// might differ from ToType in its cv-qualifiers at some level) into
1204/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001205///
Douglas Gregora29dc052008-11-27 01:19:21 +00001206/// This routine also supports conversions to and from block pointers
1207/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1208/// pointers to interfaces. FIXME: Once we've determined the
1209/// appropriate overloading rules for Objective-C, we may want to
1210/// split the Objective-C checks into a different routine; however,
1211/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001212/// conversions, so for now they live here. IncompatibleObjC will be
1213/// set if the conversion is an allowed Objective-C conversion that
1214/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001215bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001216 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001217 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001218 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001219 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001220 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1221 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001222
Mike Stump11289f42009-09-09 15:08:12 +00001223 // Conversion from a null pointer constant to any Objective-C pointer type.
1224 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001225 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001226 ConvertedType = ToType;
1227 return true;
1228 }
1229
Douglas Gregor231d1c62008-11-27 00:15:41 +00001230 // Blocks: Block pointers can be converted to void*.
1231 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001232 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001233 ConvertedType = ToType;
1234 return true;
1235 }
1236 // Blocks: A null pointer constant can be converted to a block
1237 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001238 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001239 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001240 ConvertedType = ToType;
1241 return true;
1242 }
1243
Sebastian Redl576fd422009-05-10 18:38:11 +00001244 // If the left-hand-side is nullptr_t, the right side can be a null
1245 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001246 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001247 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001248 ConvertedType = ToType;
1249 return true;
1250 }
1251
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001252 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001253 if (!ToTypePtr)
1254 return false;
1255
1256 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001257 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258 ConvertedType = ToType;
1259 return true;
1260 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001261
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001262 // Beyond this point, both types need to be pointers
1263 // , including objective-c pointers.
1264 QualType ToPointeeType = ToTypePtr->getPointeeType();
1265 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1266 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1267 ToType, Context);
1268 return true;
1269
1270 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001271 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001272 if (!FromTypePtr)
1273 return false;
1274
1275 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001276
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001277 // An rvalue of type "pointer to cv T," where T is an object type,
1278 // can be converted to an rvalue of type "pointer to cv void" (C++
1279 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001280 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001281 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001282 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001283 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001284 return true;
1285 }
1286
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001287 // When we're overloading in C, we allow a special kind of pointer
1288 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001289 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001290 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001291 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001292 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001293 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001294 return true;
1295 }
1296
Douglas Gregor5c407d92008-10-23 00:40:37 +00001297 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001298 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001299 // An rvalue of type "pointer to cv D," where D is a class type,
1300 // can be converted to an rvalue of type "pointer to cv B," where
1301 // B is a base class (clause 10) of D. If B is an inaccessible
1302 // (clause 11) or ambiguous (10.2) base class of D, a program that
1303 // necessitates this conversion is ill-formed. The result of the
1304 // conversion is a pointer to the base class sub-object of the
1305 // derived class object. The null pointer value is converted to
1306 // the null pointer value of the destination type.
1307 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001308 // Note that we do not check for ambiguity or inaccessibility
1309 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001310 if (getLangOptions().CPlusPlus &&
1311 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001312 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001313 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001314 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001315 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001316 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001317 ToType, Context);
1318 return true;
1319 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001320
Douglas Gregora119f102008-12-19 19:13:09 +00001321 return false;
1322}
1323
1324/// isObjCPointerConversion - Determines whether this is an
1325/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1326/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001327bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001328 QualType& ConvertedType,
1329 bool &IncompatibleObjC) {
1330 if (!getLangOptions().ObjC1)
1331 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001332
Steve Naroff7cae42b2009-07-10 23:34:53 +00001333 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001334 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001335 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001336 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001337
Steve Naroff7cae42b2009-07-10 23:34:53 +00001338 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001339 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001340 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001341 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001342 ConvertedType = ToType;
1343 return true;
1344 }
1345 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001346 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001347 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001348 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001349 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001350 ConvertedType = ToType;
1351 return true;
1352 }
1353 // Objective C++: We're able to convert from a pointer to an
1354 // interface to a pointer to a different interface.
1355 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001356 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1357 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1358 if (getLangOptions().CPlusPlus && LHS && RHS &&
1359 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1360 FromObjCPtr->getPointeeType()))
1361 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001362 ConvertedType = ToType;
1363 return true;
1364 }
1365
1366 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1367 // Okay: this is some kind of implicit downcast of Objective-C
1368 // interfaces, which is permitted. However, we're going to
1369 // complain about it.
1370 IncompatibleObjC = true;
1371 ConvertedType = FromType;
1372 return true;
1373 }
Mike Stump11289f42009-09-09 15:08:12 +00001374 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001375 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001376 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001377 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001378 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001379 else if (const BlockPointerType *ToBlockPtr =
1380 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001381 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001382 // to a block pointer type.
1383 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1384 ConvertedType = ToType;
1385 return true;
1386 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001387 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001388 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001389 else if (FromType->getAs<BlockPointerType>() &&
1390 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1391 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001392 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001393 ConvertedType = ToType;
1394 return true;
1395 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001396 else
Douglas Gregora119f102008-12-19 19:13:09 +00001397 return false;
1398
Douglas Gregor033f56d2008-12-23 00:53:59 +00001399 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001400 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001401 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001402 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001403 FromPointeeType = FromBlockPtr->getPointeeType();
1404 else
Douglas Gregora119f102008-12-19 19:13:09 +00001405 return false;
1406
Douglas Gregora119f102008-12-19 19:13:09 +00001407 // If we have pointers to pointers, recursively check whether this
1408 // is an Objective-C conversion.
1409 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1410 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1411 IncompatibleObjC)) {
1412 // We always complain about this conversion.
1413 IncompatibleObjC = true;
1414 ConvertedType = ToType;
1415 return true;
1416 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001417 // Allow conversion of pointee being objective-c pointer to another one;
1418 // as in I* to id.
1419 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1420 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1421 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1422 IncompatibleObjC)) {
1423 ConvertedType = ToType;
1424 return true;
1425 }
1426
Douglas Gregor033f56d2008-12-23 00:53:59 +00001427 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001428 // differences in the argument and result types are in Objective-C
1429 // pointer conversions. If so, we permit the conversion (but
1430 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001431 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001432 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001433 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001434 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001435 if (FromFunctionType && ToFunctionType) {
1436 // If the function types are exactly the same, this isn't an
1437 // Objective-C pointer conversion.
1438 if (Context.getCanonicalType(FromPointeeType)
1439 == Context.getCanonicalType(ToPointeeType))
1440 return false;
1441
1442 // Perform the quick checks that will tell us whether these
1443 // function types are obviously different.
1444 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1445 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1446 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1447 return false;
1448
1449 bool HasObjCConversion = false;
1450 if (Context.getCanonicalType(FromFunctionType->getResultType())
1451 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1452 // Okay, the types match exactly. Nothing to do.
1453 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1454 ToFunctionType->getResultType(),
1455 ConvertedType, IncompatibleObjC)) {
1456 // Okay, we have an Objective-C pointer conversion.
1457 HasObjCConversion = true;
1458 } else {
1459 // Function types are too different. Abort.
1460 return false;
1461 }
Mike Stump11289f42009-09-09 15:08:12 +00001462
Douglas Gregora119f102008-12-19 19:13:09 +00001463 // Check argument types.
1464 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1465 ArgIdx != NumArgs; ++ArgIdx) {
1466 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1467 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1468 if (Context.getCanonicalType(FromArgType)
1469 == Context.getCanonicalType(ToArgType)) {
1470 // Okay, the types match exactly. Nothing to do.
1471 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1472 ConvertedType, IncompatibleObjC)) {
1473 // Okay, we have an Objective-C pointer conversion.
1474 HasObjCConversion = true;
1475 } else {
1476 // Argument types are too different. Abort.
1477 return false;
1478 }
1479 }
1480
1481 if (HasObjCConversion) {
1482 // We had an Objective-C conversion. Allow this pointer
1483 // conversion, but complain about it.
1484 ConvertedType = ToType;
1485 IncompatibleObjC = true;
1486 return true;
1487 }
1488 }
1489
Sebastian Redl72b597d2009-01-25 19:43:20 +00001490 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001491}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001492
1493/// FunctionArgTypesAreEqual - This routine checks two function proto types
1494/// for equlity of their argument types. Caller has already checked that
1495/// they have same number of arguments. This routine assumes that Objective-C
1496/// pointer types which only differ in their protocol qualifiers are equal.
1497bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1498 FunctionProtoType* NewType){
1499 if (!getLangOptions().ObjC1)
1500 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1501 NewType->arg_type_begin());
1502
1503 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1504 N = NewType->arg_type_begin(),
1505 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1506 QualType ToType = (*O);
1507 QualType FromType = (*N);
1508 if (ToType != FromType) {
1509 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1510 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001511 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1512 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1513 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1514 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001515 continue;
1516 }
1517 else if (ToType->isObjCObjectPointerType() &&
1518 FromType->isObjCObjectPointerType()) {
1519 QualType ToInterfaceTy = ToType->getPointeeType();
1520 QualType FromInterfaceTy = FromType->getPointeeType();
1521 if (const ObjCInterfaceType *OITTo =
1522 ToInterfaceTy->getAs<ObjCInterfaceType>())
1523 if (const ObjCInterfaceType *OITFr =
1524 FromInterfaceTy->getAs<ObjCInterfaceType>())
1525 if (OITTo->getDecl() == OITFr->getDecl())
1526 continue;
1527 }
1528 return false;
1529 }
1530 }
1531 return true;
1532}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533
Douglas Gregor39c16d42008-10-24 04:54:22 +00001534/// CheckPointerConversion - Check the pointer conversion from the
1535/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001536/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001537/// conversions for which IsPointerConversion has already returned
1538/// true. It returns true and produces a diagnostic if there was an
1539/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001540bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001541 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001542 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001543 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001544 QualType FromType = From->getType();
1545
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001546 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1547 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001548 QualType FromPointeeType = FromPtrType->getPointeeType(),
1549 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001550
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001551 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1552 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001553 // We must have a derived-to-base conversion. Check an
1554 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001555 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1556 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001557 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001558 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001559 return true;
1560
1561 // The conversion was successful.
1562 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001563 }
1564 }
Mike Stump11289f42009-09-09 15:08:12 +00001565 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001566 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001567 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001568 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001569 // Objective-C++ conversions are always okay.
1570 // FIXME: We should have a different class of conversions for the
1571 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001572 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001573 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001574
Steve Naroff7cae42b2009-07-10 23:34:53 +00001575 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001576 return false;
1577}
1578
Sebastian Redl72b597d2009-01-25 19:43:20 +00001579/// IsMemberPointerConversion - Determines whether the conversion of the
1580/// expression From, which has the (possibly adjusted) type FromType, can be
1581/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1582/// If so, returns true and places the converted type (that might differ from
1583/// ToType in its cv-qualifiers at some level) into ConvertedType.
1584bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001585 QualType ToType,
1586 bool InOverloadResolution,
1587 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001588 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001589 if (!ToTypePtr)
1590 return false;
1591
1592 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001593 if (From->isNullPointerConstant(Context,
1594 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1595 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001596 ConvertedType = ToType;
1597 return true;
1598 }
1599
1600 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001601 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001602 if (!FromTypePtr)
1603 return false;
1604
1605 // A pointer to member of B can be converted to a pointer to member of D,
1606 // where D is derived from B (C++ 4.11p2).
1607 QualType FromClass(FromTypePtr->getClass(), 0);
1608 QualType ToClass(ToTypePtr->getClass(), 0);
1609 // FIXME: What happens when these are dependent? Is this function even called?
1610
1611 if (IsDerivedFrom(ToClass, FromClass)) {
1612 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1613 ToClass.getTypePtr());
1614 return true;
1615 }
1616
1617 return false;
1618}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001619
Sebastian Redl72b597d2009-01-25 19:43:20 +00001620/// CheckMemberPointerConversion - Check the member pointer conversion from the
1621/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001622/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001623/// for which IsMemberPointerConversion has already returned true. It returns
1624/// true and produces a diagnostic if there was an error, or returns false
1625/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001626bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001627 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001628 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001629 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001630 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001631 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001632 if (!FromPtrType) {
1633 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001634 assert(From->isNullPointerConstant(Context,
1635 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001636 "Expr must be null pointer constant!");
1637 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001638 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001639 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001640
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001641 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001642 assert(ToPtrType && "No member pointer cast has a target type "
1643 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001644
Sebastian Redled8f2002009-01-28 18:33:18 +00001645 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1646 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001647
Sebastian Redled8f2002009-01-28 18:33:18 +00001648 // FIXME: What about dependent types?
1649 assert(FromClass->isRecordType() && "Pointer into non-class.");
1650 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001651
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001652 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001653 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001654 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1655 assert(DerivationOkay &&
1656 "Should not have been called if derivation isn't OK.");
1657 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001658
Sebastian Redled8f2002009-01-28 18:33:18 +00001659 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1660 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001661 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1662 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1663 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1664 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001665 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001666
Douglas Gregor89ee6822009-02-28 01:32:25 +00001667 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001668 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1669 << FromClass << ToClass << QualType(VBase, 0)
1670 << From->getSourceRange();
1671 return true;
1672 }
1673
John McCall5b0829a2010-02-10 09:31:12 +00001674 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001675 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1676 Paths.front(),
1677 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001678
Anders Carlssond7923c62009-08-22 23:33:40 +00001679 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001680 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001681 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001682 return false;
1683}
1684
Douglas Gregor9a657932008-10-21 23:43:52 +00001685/// IsQualificationConversion - Determines whether the conversion from
1686/// an rvalue of type FromType to ToType is a qualification conversion
1687/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001688bool
1689Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001690 FromType = Context.getCanonicalType(FromType);
1691 ToType = Context.getCanonicalType(ToType);
1692
1693 // If FromType and ToType are the same type, this is not a
1694 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001695 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001696 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001697
Douglas Gregor9a657932008-10-21 23:43:52 +00001698 // (C++ 4.4p4):
1699 // A conversion can add cv-qualifiers at levels other than the first
1700 // in multi-level pointers, subject to the following rules: [...]
1701 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001702 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001703 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001704 // Within each iteration of the loop, we check the qualifiers to
1705 // determine if this still looks like a qualification
1706 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001707 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001708 // until there are no more pointers or pointers-to-members left to
1709 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001710 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001711
1712 // -- for every j > 0, if const is in cv 1,j then const is in cv
1713 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001714 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001715 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001716
Douglas Gregor9a657932008-10-21 23:43:52 +00001717 // -- if the cv 1,j and cv 2,j are different, then const is in
1718 // every cv for 0 < k < j.
1719 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001720 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001721 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001722
Douglas Gregor9a657932008-10-21 23:43:52 +00001723 // Keep track of whether all prior cv-qualifiers in the "to" type
1724 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001725 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001726 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001727 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001728
1729 // We are left with FromType and ToType being the pointee types
1730 // after unwrapping the original FromType and ToType the same number
1731 // of types. If we unwrapped any pointers, and if FromType and
1732 // ToType have the same unqualified type (since we checked
1733 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001734 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001735}
1736
Douglas Gregor576e98c2009-01-30 23:27:23 +00001737/// Determines whether there is a user-defined conversion sequence
1738/// (C++ [over.ics.user]) that converts expression From to the type
1739/// ToType. If such a conversion exists, User will contain the
1740/// user-defined conversion sequence that performs such a conversion
1741/// and this routine will return true. Otherwise, this routine returns
1742/// false and User is unspecified.
1743///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001744/// \param AllowExplicit true if the conversion should consider C++0x
1745/// "explicit" conversion functions as well as non-explicit conversion
1746/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001747OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1748 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001749 OverloadCandidateSet& CandidateSet,
1750 bool AllowExplicit) {
1751 // Whether we will only visit constructors.
1752 bool ConstructorsOnly = false;
1753
1754 // If the type we are conversion to is a class type, enumerate its
1755 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001756 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001757 // C++ [over.match.ctor]p1:
1758 // When objects of class type are direct-initialized (8.5), or
1759 // copy-initialized from an expression of the same or a
1760 // derived class type (8.5), overload resolution selects the
1761 // constructor. [...] For copy-initialization, the candidate
1762 // functions are all the converting constructors (12.3.1) of
1763 // that class. The argument list is the expression-list within
1764 // the parentheses of the initializer.
1765 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1766 (From->getType()->getAs<RecordType>() &&
1767 IsDerivedFrom(From->getType(), ToType)))
1768 ConstructorsOnly = true;
1769
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001770 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1771 // We're not going to find any constructors.
1772 } else if (CXXRecordDecl *ToRecordDecl
1773 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001774 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001775 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001776 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001777 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001778 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001779 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001780 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001781 NamedDecl *D = *Con;
1782 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1783
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001784 // Find the constructor (which may be a template).
1785 CXXConstructorDecl *Constructor = 0;
1786 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001787 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001788 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001789 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001790 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1791 else
John McCalla0296f72010-03-19 07:35:19 +00001792 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001793
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001794 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001795 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001796 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001797 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001798 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001799 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001800 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001801 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001802 // Allow one user-defined conversion when user specifies a
1803 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001804 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001805 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001806 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001807 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001808 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001809 }
1810 }
1811
Douglas Gregor5ab11652010-04-17 22:01:05 +00001812 // Enumerate conversion functions, if we're allowed to.
1813 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001814 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001815 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001816 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001817 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001818 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001819 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001820 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1821 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001822 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001823 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001824 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001825 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001826 DeclAccessPair FoundDecl = I.getPair();
1827 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001828 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1829 if (isa<UsingShadowDecl>(D))
1830 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1831
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001832 CXXConversionDecl *Conv;
1833 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001834 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1835 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001836 else
John McCallda4458e2010-03-31 01:36:47 +00001837 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001838
1839 if (AllowExplicit || !Conv->isExplicit()) {
1840 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001841 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001842 ActingContext, From, ToType,
1843 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001844 else
John McCalla0296f72010-03-19 07:35:19 +00001845 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001846 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001847 }
1848 }
1849 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001850 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001851
1852 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001853 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001854 case OR_Success:
1855 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001856 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001857 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1858 // C++ [over.ics.user]p1:
1859 // If the user-defined conversion is specified by a
1860 // constructor (12.3.1), the initial standard conversion
1861 // sequence converts the source type to the type required by
1862 // the argument of the constructor.
1863 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001864 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001865 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001866 User.EllipsisConversion = true;
1867 else {
1868 User.Before = Best->Conversions[0].Standard;
1869 User.EllipsisConversion = false;
1870 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001871 User.ConversionFunction = Constructor;
1872 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001873 User.After.setFromType(
1874 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001875 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001876 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001877 } else if (CXXConversionDecl *Conversion
1878 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1879 // C++ [over.ics.user]p1:
1880 //
1881 // [...] If the user-defined conversion is specified by a
1882 // conversion function (12.3.2), the initial standard
1883 // conversion sequence converts the source type to the
1884 // implicit object parameter of the conversion function.
1885 User.Before = Best->Conversions[0].Standard;
1886 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001887 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001888
1889 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001890 // The second standard conversion sequence converts the
1891 // result of the user-defined conversion to the target type
1892 // for the sequence. Since an implicit conversion sequence
1893 // is an initialization, the special rules for
1894 // initialization by user-defined conversion apply when
1895 // selecting the best user-defined conversion for a
1896 // user-defined conversion sequence (see 13.3.3 and
1897 // 13.3.3.1).
1898 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001899 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001900 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001901 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001902 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001903 }
Mike Stump11289f42009-09-09 15:08:12 +00001904
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001905 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001906 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001907 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001908 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001909 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001910
1911 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001912 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001913 }
1914
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001915 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001916}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001917
1918bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001919Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001920 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001921 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001922 OverloadingResult OvResult =
1923 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001924 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001925 if (OvResult == OR_Ambiguous)
1926 Diag(From->getSourceRange().getBegin(),
1927 diag::err_typecheck_ambiguous_condition)
1928 << From->getType() << ToType << From->getSourceRange();
1929 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1930 Diag(From->getSourceRange().getBegin(),
1931 diag::err_typecheck_nonviable_condition)
1932 << From->getType() << ToType << From->getSourceRange();
1933 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001934 return false;
John McCallad907772010-01-12 07:18:19 +00001935 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001936 return true;
1937}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001938
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001939/// CompareImplicitConversionSequences - Compare two implicit
1940/// conversion sequences to determine whether one is better than the
1941/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001942ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001943Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1944 const ImplicitConversionSequence& ICS2)
1945{
1946 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1947 // conversion sequences (as defined in 13.3.3.1)
1948 // -- a standard conversion sequence (13.3.3.1.1) is a better
1949 // conversion sequence than a user-defined conversion sequence or
1950 // an ellipsis conversion sequence, and
1951 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1952 // conversion sequence than an ellipsis conversion sequence
1953 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001954 //
John McCall0d1da222010-01-12 00:44:57 +00001955 // C++0x [over.best.ics]p10:
1956 // For the purpose of ranking implicit conversion sequences as
1957 // described in 13.3.3.2, the ambiguous conversion sequence is
1958 // treated as a user-defined sequence that is indistinguishable
1959 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00001960 if (ICS1.getKindRank() < ICS2.getKindRank())
1961 return ImplicitConversionSequence::Better;
1962 else if (ICS2.getKindRank() < ICS1.getKindRank())
1963 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001964
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00001965 // The following checks require both conversion sequences to be of
1966 // the same kind.
1967 if (ICS1.getKind() != ICS2.getKind())
1968 return ImplicitConversionSequence::Indistinguishable;
1969
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001970 // Two implicit conversion sequences of the same form are
1971 // indistinguishable conversion sequences unless one of the
1972 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001973 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001974 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001975 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001976 // User-defined conversion sequence U1 is a better conversion
1977 // sequence than another user-defined conversion sequence U2 if
1978 // they contain the same user-defined conversion function or
1979 // constructor and if the second standard conversion sequence of
1980 // U1 is better than the second standard conversion sequence of
1981 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001982 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001983 ICS2.UserDefined.ConversionFunction)
1984 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1985 ICS2.UserDefined.After);
1986 }
1987
1988 return ImplicitConversionSequence::Indistinguishable;
1989}
1990
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001991// Per 13.3.3.2p3, compare the given standard conversion sequences to
1992// determine if one is a proper subset of the other.
1993static ImplicitConversionSequence::CompareKind
1994compareStandardConversionSubsets(ASTContext &Context,
1995 const StandardConversionSequence& SCS1,
1996 const StandardConversionSequence& SCS2) {
1997 ImplicitConversionSequence::CompareKind Result
1998 = ImplicitConversionSequence::Indistinguishable;
1999
2000 if (SCS1.Second != SCS2.Second) {
2001 if (SCS1.Second == ICK_Identity)
2002 Result = ImplicitConversionSequence::Better;
2003 else if (SCS2.Second == ICK_Identity)
2004 Result = ImplicitConversionSequence::Worse;
2005 else
2006 return ImplicitConversionSequence::Indistinguishable;
2007 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
2008 return ImplicitConversionSequence::Indistinguishable;
2009
2010 if (SCS1.Third == SCS2.Third) {
2011 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2012 : ImplicitConversionSequence::Indistinguishable;
2013 }
2014
2015 if (SCS1.Third == ICK_Identity)
2016 return Result == ImplicitConversionSequence::Worse
2017 ? ImplicitConversionSequence::Indistinguishable
2018 : ImplicitConversionSequence::Better;
2019
2020 if (SCS2.Third == ICK_Identity)
2021 return Result == ImplicitConversionSequence::Better
2022 ? ImplicitConversionSequence::Indistinguishable
2023 : ImplicitConversionSequence::Worse;
2024
2025 return ImplicitConversionSequence::Indistinguishable;
2026}
2027
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002028/// CompareStandardConversionSequences - Compare two standard
2029/// conversion sequences to determine whether one is better than the
2030/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002031ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002032Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2033 const StandardConversionSequence& SCS2)
2034{
2035 // Standard conversion sequence S1 is a better conversion sequence
2036 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2037
2038 // -- S1 is a proper subsequence of S2 (comparing the conversion
2039 // sequences in the canonical form defined by 13.3.3.1.1,
2040 // excluding any Lvalue Transformation; the identity conversion
2041 // sequence is considered to be a subsequence of any
2042 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002043 if (ImplicitConversionSequence::CompareKind CK
2044 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2045 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002046
2047 // -- the rank of S1 is better than the rank of S2 (by the rules
2048 // defined below), or, if not that,
2049 ImplicitConversionRank Rank1 = SCS1.getRank();
2050 ImplicitConversionRank Rank2 = SCS2.getRank();
2051 if (Rank1 < Rank2)
2052 return ImplicitConversionSequence::Better;
2053 else if (Rank2 < Rank1)
2054 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002055
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002056 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2057 // are indistinguishable unless one of the following rules
2058 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002059
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002060 // A conversion that is not a conversion of a pointer, or
2061 // pointer to member, to bool is better than another conversion
2062 // that is such a conversion.
2063 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2064 return SCS2.isPointerConversionToBool()
2065 ? ImplicitConversionSequence::Better
2066 : ImplicitConversionSequence::Worse;
2067
Douglas Gregor5c407d92008-10-23 00:40:37 +00002068 // C++ [over.ics.rank]p4b2:
2069 //
2070 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002071 // conversion of B* to A* is better than conversion of B* to
2072 // void*, and conversion of A* to void* is better than conversion
2073 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002074 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002075 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002076 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002077 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002078 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2079 // Exactly one of the conversion sequences is a conversion to
2080 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002081 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2082 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002083 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2084 // Neither conversion sequence converts to a void pointer; compare
2085 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002086 if (ImplicitConversionSequence::CompareKind DerivedCK
2087 = CompareDerivedToBaseConversions(SCS1, SCS2))
2088 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002089 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2090 // Both conversion sequences are conversions to void
2091 // pointers. Compare the source types to determine if there's an
2092 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002093 QualType FromType1 = SCS1.getFromType();
2094 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002095
2096 // Adjust the types we're converting from via the array-to-pointer
2097 // conversion, if we need to.
2098 if (SCS1.First == ICK_Array_To_Pointer)
2099 FromType1 = Context.getArrayDecayedType(FromType1);
2100 if (SCS2.First == ICK_Array_To_Pointer)
2101 FromType2 = Context.getArrayDecayedType(FromType2);
2102
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002103 QualType FromPointee1
2104 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2105 QualType FromPointee2
2106 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002107
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002108 if (IsDerivedFrom(FromPointee2, FromPointee1))
2109 return ImplicitConversionSequence::Better;
2110 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2111 return ImplicitConversionSequence::Worse;
2112
2113 // Objective-C++: If one interface is more specific than the
2114 // other, it is the better one.
2115 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2116 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2117 if (FromIface1 && FromIface1) {
2118 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2119 return ImplicitConversionSequence::Better;
2120 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2121 return ImplicitConversionSequence::Worse;
2122 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002123 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002124
2125 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2126 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002127 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002128 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002129 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002130
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002131 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002132 // C++0x [over.ics.rank]p3b4:
2133 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2134 // implicit object parameter of a non-static member function declared
2135 // without a ref-qualifier, and S1 binds an rvalue reference to an
2136 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002137 // FIXME: We don't know if we're dealing with the implicit object parameter,
2138 // or if the member function in this case has a ref qualifier.
2139 // (Of course, we don't have ref qualifiers yet.)
2140 if (SCS1.RRefBinding != SCS2.RRefBinding)
2141 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2142 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002143
2144 // C++ [over.ics.rank]p3b4:
2145 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2146 // which the references refer are the same type except for
2147 // top-level cv-qualifiers, and the type to which the reference
2148 // initialized by S2 refers is more cv-qualified than the type
2149 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002150 QualType T1 = SCS1.getToType(2);
2151 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002152 T1 = Context.getCanonicalType(T1);
2153 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002154 Qualifiers T1Quals, T2Quals;
2155 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2156 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2157 if (UnqualT1 == UnqualT2) {
2158 // If the type is an array type, promote the element qualifiers to the type
2159 // for comparison.
2160 if (isa<ArrayType>(T1) && T1Quals)
2161 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2162 if (isa<ArrayType>(T2) && T2Quals)
2163 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002164 if (T2.isMoreQualifiedThan(T1))
2165 return ImplicitConversionSequence::Better;
2166 else if (T1.isMoreQualifiedThan(T2))
2167 return ImplicitConversionSequence::Worse;
2168 }
2169 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002170
2171 return ImplicitConversionSequence::Indistinguishable;
2172}
2173
2174/// CompareQualificationConversions - Compares two standard conversion
2175/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002176/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2177ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002178Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002179 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002180 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002181 // -- S1 and S2 differ only in their qualification conversion and
2182 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2183 // cv-qualification signature of type T1 is a proper subset of
2184 // the cv-qualification signature of type T2, and S1 is not the
2185 // deprecated string literal array-to-pointer conversion (4.2).
2186 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2187 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2188 return ImplicitConversionSequence::Indistinguishable;
2189
2190 // FIXME: the example in the standard doesn't use a qualification
2191 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002192 QualType T1 = SCS1.getToType(2);
2193 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002194 T1 = Context.getCanonicalType(T1);
2195 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002196 Qualifiers T1Quals, T2Quals;
2197 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2198 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002199
2200 // If the types are the same, we won't learn anything by unwrapped
2201 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002202 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002203 return ImplicitConversionSequence::Indistinguishable;
2204
Chandler Carruth607f38e2009-12-29 07:16:59 +00002205 // If the type is an array type, promote the element qualifiers to the type
2206 // for comparison.
2207 if (isa<ArrayType>(T1) && T1Quals)
2208 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2209 if (isa<ArrayType>(T2) && T2Quals)
2210 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2211
Mike Stump11289f42009-09-09 15:08:12 +00002212 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002213 = ImplicitConversionSequence::Indistinguishable;
2214 while (UnwrapSimilarPointerTypes(T1, T2)) {
2215 // Within each iteration of the loop, we check the qualifiers to
2216 // determine if this still looks like a qualification
2217 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002218 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002219 // until there are no more pointers or pointers-to-members left
2220 // to unwrap. This essentially mimics what
2221 // IsQualificationConversion does, but here we're checking for a
2222 // strict subset of qualifiers.
2223 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2224 // The qualifiers are the same, so this doesn't tell us anything
2225 // about how the sequences rank.
2226 ;
2227 else if (T2.isMoreQualifiedThan(T1)) {
2228 // T1 has fewer qualifiers, so it could be the better sequence.
2229 if (Result == ImplicitConversionSequence::Worse)
2230 // Neither has qualifiers that are a subset of the other's
2231 // qualifiers.
2232 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002233
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002234 Result = ImplicitConversionSequence::Better;
2235 } else if (T1.isMoreQualifiedThan(T2)) {
2236 // T2 has fewer qualifiers, so it could be the better sequence.
2237 if (Result == ImplicitConversionSequence::Better)
2238 // Neither has qualifiers that are a subset of the other's
2239 // qualifiers.
2240 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002241
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002242 Result = ImplicitConversionSequence::Worse;
2243 } else {
2244 // Qualifiers are disjoint.
2245 return ImplicitConversionSequence::Indistinguishable;
2246 }
2247
2248 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002249 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002250 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002251 }
2252
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002253 // Check that the winning standard conversion sequence isn't using
2254 // the deprecated string literal array to pointer conversion.
2255 switch (Result) {
2256 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002257 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002258 Result = ImplicitConversionSequence::Indistinguishable;
2259 break;
2260
2261 case ImplicitConversionSequence::Indistinguishable:
2262 break;
2263
2264 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002265 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002266 Result = ImplicitConversionSequence::Indistinguishable;
2267 break;
2268 }
2269
2270 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002271}
2272
Douglas Gregor5c407d92008-10-23 00:40:37 +00002273/// CompareDerivedToBaseConversions - Compares two standard conversion
2274/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002275/// various kinds of derived-to-base conversions (C++
2276/// [over.ics.rank]p4b3). As part of these checks, we also look at
2277/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002278ImplicitConversionSequence::CompareKind
2279Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2280 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002281 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002282 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002283 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002284 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002285
2286 // Adjust the types we're converting from via the array-to-pointer
2287 // conversion, if we need to.
2288 if (SCS1.First == ICK_Array_To_Pointer)
2289 FromType1 = Context.getArrayDecayedType(FromType1);
2290 if (SCS2.First == ICK_Array_To_Pointer)
2291 FromType2 = Context.getArrayDecayedType(FromType2);
2292
2293 // Canonicalize all of the types.
2294 FromType1 = Context.getCanonicalType(FromType1);
2295 ToType1 = Context.getCanonicalType(ToType1);
2296 FromType2 = Context.getCanonicalType(FromType2);
2297 ToType2 = Context.getCanonicalType(ToType2);
2298
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002299 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002300 //
2301 // If class B is derived directly or indirectly from class A and
2302 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002303 //
2304 // For Objective-C, we let A, B, and C also be Objective-C
2305 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002306
2307 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002308 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002309 SCS2.Second == ICK_Pointer_Conversion &&
2310 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2311 FromType1->isPointerType() && FromType2->isPointerType() &&
2312 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002313 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002314 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002315 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002316 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002317 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002318 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002319 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002320 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002321
John McCall9dd450b2009-09-21 23:43:11 +00002322 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2323 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2324 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2325 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002326
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002327 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002328 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2329 if (IsDerivedFrom(ToPointee1, ToPointee2))
2330 return ImplicitConversionSequence::Better;
2331 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2332 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002333
2334 if (ToIface1 && ToIface2) {
2335 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2336 return ImplicitConversionSequence::Better;
2337 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2338 return ImplicitConversionSequence::Worse;
2339 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002340 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002341
2342 // -- conversion of B* to A* is better than conversion of C* to A*,
2343 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2344 if (IsDerivedFrom(FromPointee2, FromPointee1))
2345 return ImplicitConversionSequence::Better;
2346 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2347 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002348
Douglas Gregor237f96c2008-11-26 23:31:11 +00002349 if (FromIface1 && FromIface2) {
2350 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2351 return ImplicitConversionSequence::Better;
2352 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2353 return ImplicitConversionSequence::Worse;
2354 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002355 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002356 }
2357
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002358 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002359 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2360 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2361 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2362 const MemberPointerType * FromMemPointer1 =
2363 FromType1->getAs<MemberPointerType>();
2364 const MemberPointerType * ToMemPointer1 =
2365 ToType1->getAs<MemberPointerType>();
2366 const MemberPointerType * FromMemPointer2 =
2367 FromType2->getAs<MemberPointerType>();
2368 const MemberPointerType * ToMemPointer2 =
2369 ToType2->getAs<MemberPointerType>();
2370 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2371 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2372 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2373 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2374 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2375 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2376 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2377 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002378 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002379 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2380 if (IsDerivedFrom(ToPointee1, ToPointee2))
2381 return ImplicitConversionSequence::Worse;
2382 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2383 return ImplicitConversionSequence::Better;
2384 }
2385 // conversion of B::* to C::* is better than conversion of A::* to C::*
2386 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2387 if (IsDerivedFrom(FromPointee1, FromPointee2))
2388 return ImplicitConversionSequence::Better;
2389 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2390 return ImplicitConversionSequence::Worse;
2391 }
2392 }
2393
Douglas Gregor5ab11652010-04-17 22:01:05 +00002394 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002395 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002396 // -- binding of an expression of type C to a reference of type
2397 // B& is better than binding an expression of type C to a
2398 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002399 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2400 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002401 if (IsDerivedFrom(ToType1, ToType2))
2402 return ImplicitConversionSequence::Better;
2403 else if (IsDerivedFrom(ToType2, ToType1))
2404 return ImplicitConversionSequence::Worse;
2405 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002406
Douglas Gregor2fe98832008-11-03 19:09:14 +00002407 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002408 // -- binding of an expression of type B to a reference of type
2409 // A& is better than binding an expression of type C to a
2410 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002411 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2412 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002413 if (IsDerivedFrom(FromType2, FromType1))
2414 return ImplicitConversionSequence::Better;
2415 else if (IsDerivedFrom(FromType1, FromType2))
2416 return ImplicitConversionSequence::Worse;
2417 }
2418 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002419
Douglas Gregor5c407d92008-10-23 00:40:37 +00002420 return ImplicitConversionSequence::Indistinguishable;
2421}
2422
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002423/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2424/// determine whether they are reference-related,
2425/// reference-compatible, reference-compatible with added
2426/// qualification, or incompatible, for use in C++ initialization by
2427/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2428/// type, and the first type (T1) is the pointee type of the reference
2429/// type being initialized.
2430Sema::ReferenceCompareResult
2431Sema::CompareReferenceRelationship(SourceLocation Loc,
2432 QualType OrigT1, QualType OrigT2,
2433 bool& DerivedToBase) {
2434 assert(!OrigT1->isReferenceType() &&
2435 "T1 must be the pointee type of the reference type");
2436 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2437
2438 QualType T1 = Context.getCanonicalType(OrigT1);
2439 QualType T2 = Context.getCanonicalType(OrigT2);
2440 Qualifiers T1Quals, T2Quals;
2441 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2442 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2443
2444 // C++ [dcl.init.ref]p4:
2445 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2446 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2447 // T1 is a base class of T2.
2448 if (UnqualT1 == UnqualT2)
2449 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002450 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002451 IsDerivedFrom(UnqualT2, UnqualT1))
2452 DerivedToBase = true;
2453 else
2454 return Ref_Incompatible;
2455
2456 // At this point, we know that T1 and T2 are reference-related (at
2457 // least).
2458
2459 // If the type is an array type, promote the element qualifiers to the type
2460 // for comparison.
2461 if (isa<ArrayType>(T1) && T1Quals)
2462 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2463 if (isa<ArrayType>(T2) && T2Quals)
2464 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2465
2466 // C++ [dcl.init.ref]p4:
2467 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2468 // reference-related to T2 and cv1 is the same cv-qualification
2469 // as, or greater cv-qualification than, cv2. For purposes of
2470 // overload resolution, cases for which cv1 is greater
2471 // cv-qualification than cv2 are identified as
2472 // reference-compatible with added qualification (see 13.3.3.2).
2473 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2474 return Ref_Compatible;
2475 else if (T1.isMoreQualifiedThan(T2))
2476 return Ref_Compatible_With_Added_Qualification;
2477 else
2478 return Ref_Related;
2479}
2480
2481/// \brief Compute an implicit conversion sequence for reference
2482/// initialization.
2483static ImplicitConversionSequence
2484TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2485 SourceLocation DeclLoc,
2486 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002487 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002488 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2489
2490 // Most paths end in a failed conversion.
2491 ImplicitConversionSequence ICS;
2492 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2493
2494 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2495 QualType T2 = Init->getType();
2496
2497 // If the initializer is the address of an overloaded function, try
2498 // to resolve the overloaded function. If all goes well, T2 is the
2499 // type of the resulting function.
2500 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2501 DeclAccessPair Found;
2502 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2503 false, Found))
2504 T2 = Fn->getType();
2505 }
2506
2507 // Compute some basic properties of the types and the initializer.
2508 bool isRValRef = DeclType->isRValueReferenceType();
2509 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002510 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002511 Sema::ReferenceCompareResult RefRelationship
2512 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2513
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002514
2515 // C++ [over.ics.ref]p3:
2516 // Except for an implicit object parameter, for which see 13.3.1,
2517 // a standard conversion sequence cannot be formed if it requires
2518 // binding an lvalue reference to non-const to an rvalue or
2519 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002520 //
2521 // FIXME: DPG doesn't trust this code. It seems far too early to
2522 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002523 if (isRValRef && InitLvalue == Expr::LV_Valid)
2524 return ICS;
2525
Douglas Gregor870f3742010-04-18 09:22:00 +00002526 // C++0x [dcl.init.ref]p16:
2527 // A reference to type "cv1 T1" is initialized by an expression
2528 // of type "cv2 T2" as follows:
2529
2530 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002531 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2532 // reference-compatible with "cv2 T2," or
2533 //
2534 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2535 if (InitLvalue == Expr::LV_Valid &&
2536 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2537 // C++ [over.ics.ref]p1:
2538 // When a parameter of reference type binds directly (8.5.3)
2539 // to an argument expression, the implicit conversion sequence
2540 // is the identity conversion, unless the argument expression
2541 // has a type that is a derived class of the parameter type,
2542 // in which case the implicit conversion sequence is a
2543 // derived-to-base Conversion (13.3.3.1).
2544 ICS.setStandard();
2545 ICS.Standard.First = ICK_Identity;
2546 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2547 ICS.Standard.Third = ICK_Identity;
2548 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2549 ICS.Standard.setToType(0, T2);
2550 ICS.Standard.setToType(1, T1);
2551 ICS.Standard.setToType(2, T1);
2552 ICS.Standard.ReferenceBinding = true;
2553 ICS.Standard.DirectBinding = true;
2554 ICS.Standard.RRefBinding = false;
2555 ICS.Standard.CopyConstructor = 0;
2556
2557 // Nothing more to do: the inaccessibility/ambiguity check for
2558 // derived-to-base conversions is suppressed when we're
2559 // computing the implicit conversion sequence (C++
2560 // [over.best.ics]p2).
2561 return ICS;
2562 }
2563
2564 // -- has a class type (i.e., T2 is a class type), where T1 is
2565 // not reference-related to T2, and can be implicitly
2566 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2567 // is reference-compatible with "cv3 T3" 92) (this
2568 // conversion is selected by enumerating the applicable
2569 // conversion functions (13.3.1.6) and choosing the best
2570 // one through overload resolution (13.3)),
2571 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2572 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2573 RefRelationship == Sema::Ref_Incompatible) {
2574 CXXRecordDecl *T2RecordDecl
2575 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2576
2577 OverloadCandidateSet CandidateSet(DeclLoc);
2578 const UnresolvedSetImpl *Conversions
2579 = T2RecordDecl->getVisibleConversionFunctions();
2580 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2581 E = Conversions->end(); I != E; ++I) {
2582 NamedDecl *D = *I;
2583 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2584 if (isa<UsingShadowDecl>(D))
2585 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2586
2587 FunctionTemplateDecl *ConvTemplate
2588 = dyn_cast<FunctionTemplateDecl>(D);
2589 CXXConversionDecl *Conv;
2590 if (ConvTemplate)
2591 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2592 else
2593 Conv = cast<CXXConversionDecl>(D);
2594
2595 // If the conversion function doesn't return a reference type,
2596 // it can't be considered for this conversion.
2597 if (Conv->getConversionType()->isLValueReferenceType() &&
2598 (AllowExplicit || !Conv->isExplicit())) {
2599 if (ConvTemplate)
2600 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2601 Init, DeclType, CandidateSet);
2602 else
2603 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2604 DeclType, CandidateSet);
2605 }
2606 }
2607
2608 OverloadCandidateSet::iterator Best;
2609 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2610 case OR_Success:
2611 // C++ [over.ics.ref]p1:
2612 //
2613 // [...] If the parameter binds directly to the result of
2614 // applying a conversion function to the argument
2615 // expression, the implicit conversion sequence is a
2616 // user-defined conversion sequence (13.3.3.1.2), with the
2617 // second standard conversion sequence either an identity
2618 // conversion or, if the conversion function returns an
2619 // entity of a type that is a derived class of the parameter
2620 // type, a derived-to-base Conversion.
2621 if (!Best->FinalConversion.DirectBinding)
2622 break;
2623
2624 ICS.setUserDefined();
2625 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2626 ICS.UserDefined.After = Best->FinalConversion;
2627 ICS.UserDefined.ConversionFunction = Best->Function;
2628 ICS.UserDefined.EllipsisConversion = false;
2629 assert(ICS.UserDefined.After.ReferenceBinding &&
2630 ICS.UserDefined.After.DirectBinding &&
2631 "Expected a direct reference binding!");
2632 return ICS;
2633
2634 case OR_Ambiguous:
2635 ICS.setAmbiguous();
2636 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2637 Cand != CandidateSet.end(); ++Cand)
2638 if (Cand->Viable)
2639 ICS.Ambiguous.addConversion(Cand->Function);
2640 return ICS;
2641
2642 case OR_No_Viable_Function:
2643 case OR_Deleted:
2644 // There was no suitable conversion, or we found a deleted
2645 // conversion; continue with other checks.
2646 break;
2647 }
2648 }
2649
2650 // -- Otherwise, the reference shall be to a non-volatile const
2651 // type (i.e., cv1 shall be const), or the reference shall be an
2652 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002653 //
2654 // We actually handle one oddity of C++ [over.ics.ref] at this
2655 // point, which is that, due to p2 (which short-circuits reference
2656 // binding by only attempting a simple conversion for non-direct
2657 // bindings) and p3's strange wording, we allow a const volatile
2658 // reference to bind to an rvalue. Hence the check for the presence
2659 // of "const" rather than checking for "const" being the only
2660 // qualifier.
2661 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002662 return ICS;
2663
Douglas Gregorf93df192010-04-18 08:46:23 +00002664 // -- if T2 is a class type and
2665 // -- the initializer expression is an rvalue and "cv1 T1"
2666 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002667 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002668 // -- T1 is not reference-related to T2 and the initializer
2669 // expression can be implicitly converted to an rvalue
2670 // of type "cv3 T3" (this conversion is selected by
2671 // enumerating the applicable conversion functions
2672 // (13.3.1.6) and choosing the best one through overload
2673 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002674 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002675 // then the reference is bound to the initializer
2676 // expression rvalue in the first case and to the object
2677 // that is the result of the conversion in the second case
2678 // (or, in either case, to the appropriate base class
2679 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002680 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002681 // We're only checking the first case here, which is a direct
2682 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002683 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2684 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2685 ICS.setStandard();
2686 ICS.Standard.First = ICK_Identity;
2687 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2688 ICS.Standard.Third = ICK_Identity;
2689 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2690 ICS.Standard.setToType(0, T2);
2691 ICS.Standard.setToType(1, T1);
2692 ICS.Standard.setToType(2, T1);
2693 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002694 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002695 ICS.Standard.RRefBinding = isRValRef;
2696 ICS.Standard.CopyConstructor = 0;
2697 return ICS;
2698 }
2699
2700 // -- Otherwise, a temporary of type "cv1 T1" is created and
2701 // initialized from the initializer expression using the
2702 // rules for a non-reference copy initialization (8.5). The
2703 // reference is then bound to the temporary. If T1 is
2704 // reference-related to T2, cv1 must be the same
2705 // cv-qualification as, or greater cv-qualification than,
2706 // cv2; otherwise, the program is ill-formed.
2707 if (RefRelationship == Sema::Ref_Related) {
2708 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2709 // we would be reference-compatible or reference-compatible with
2710 // added qualification. But that wasn't the case, so the reference
2711 // initialization fails.
2712 return ICS;
2713 }
2714
2715 // If at least one of the types is a class type, the types are not
2716 // related, and we aren't allowed any user conversions, the
2717 // reference binding fails. This case is important for breaking
2718 // recursion, since TryImplicitConversion below will attempt to
2719 // create a temporary through the use of a copy constructor.
2720 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2721 (T1->isRecordType() || T2->isRecordType()))
2722 return ICS;
2723
2724 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002725 // When a parameter of reference type is not bound directly to
2726 // an argument expression, the conversion sequence is the one
2727 // required to convert the argument expression to the
2728 // underlying type of the reference according to
2729 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2730 // to copy-initializing a temporary of the underlying type with
2731 // the argument expression. Any difference in top-level
2732 // cv-qualification is subsumed by the initialization itself
2733 // and does not constitute a conversion.
2734 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2735 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002736 /*InOverloadResolution=*/false);
2737
2738 // Of course, that's still a reference binding.
2739 if (ICS.isStandard()) {
2740 ICS.Standard.ReferenceBinding = true;
2741 ICS.Standard.RRefBinding = isRValRef;
2742 } else if (ICS.isUserDefined()) {
2743 ICS.UserDefined.After.ReferenceBinding = true;
2744 ICS.UserDefined.After.RRefBinding = isRValRef;
2745 }
2746 return ICS;
2747}
2748
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002749/// TryCopyInitialization - Try to copy-initialize a value of type
2750/// ToType from the expression From. Return the implicit conversion
2751/// sequence required to pass this argument, which may be a bad
2752/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002753/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002754/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002755static ImplicitConversionSequence
2756TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002757 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002758 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002759 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002760 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002761 /*FIXME:*/From->getLocStart(),
2762 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002763 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002764
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002765 return S.TryImplicitConversion(From, ToType,
2766 SuppressUserConversions,
2767 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002768 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002769}
2770
Douglas Gregor436424c2008-11-18 23:14:02 +00002771/// TryObjectArgumentInitialization - Try to initialize the object
2772/// parameter of the given member function (@c Method) from the
2773/// expression @p From.
2774ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002775Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002776 CXXMethodDecl *Method,
2777 CXXRecordDecl *ActingContext) {
2778 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002779 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2780 // const volatile object.
2781 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2782 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2783 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002784
2785 // Set up the conversion sequence as a "bad" conversion, to allow us
2786 // to exit early.
2787 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002788
2789 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002790 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002791 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002792 FromType = PT->getPointeeType();
2793
2794 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002795
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002796 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002797 // where X is the class of which the function is a member
2798 // (C++ [over.match.funcs]p4). However, when finding an implicit
2799 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002800 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002801 // (C++ [over.match.funcs]p5). We perform a simplified version of
2802 // reference binding here, that allows class rvalues to bind to
2803 // non-constant references.
2804
2805 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2806 // with the implicit object parameter (C++ [over.match.funcs]p5).
2807 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002808 if (ImplicitParamType.getCVRQualifiers()
2809 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002810 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002811 ICS.setBad(BadConversionSequence::bad_qualifiers,
2812 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002813 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002814 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002815
2816 // Check that we have either the same type or a derived type. It
2817 // affects the conversion rank.
2818 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002819 ImplicitConversionKind SecondKind;
2820 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2821 SecondKind = ICK_Identity;
2822 } else if (IsDerivedFrom(FromType, ClassType))
2823 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002824 else {
John McCall65eb8792010-02-25 01:37:24 +00002825 ICS.setBad(BadConversionSequence::unrelated_class,
2826 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002827 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002828 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002829
2830 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002831 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002832 ICS.Standard.setAsIdentityConversion();
2833 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002834 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002835 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002836 ICS.Standard.ReferenceBinding = true;
2837 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002838 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002839 return ICS;
2840}
2841
2842/// PerformObjectArgumentInitialization - Perform initialization of
2843/// the implicit object parameter for the given Method with the given
2844/// expression.
2845bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002846Sema::PerformObjectArgumentInitialization(Expr *&From,
2847 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002848 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002849 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002850 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002851 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002852 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002853
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002854 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002855 FromRecordType = PT->getPointeeType();
2856 DestType = Method->getThisType(Context);
2857 } else {
2858 FromRecordType = From->getType();
2859 DestType = ImplicitParamRecordType;
2860 }
2861
John McCall6e9f8f62009-12-03 04:06:58 +00002862 // Note that we always use the true parent context when performing
2863 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002864 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002865 = TryObjectArgumentInitialization(From->getType(), Method,
2866 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002867 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002868 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002869 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002870 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002871
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002872 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002873 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002874
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002875 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002876 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2877 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002878 return false;
2879}
2880
Douglas Gregor5fb53972009-01-14 15:45:31 +00002881/// TryContextuallyConvertToBool - Attempt to contextually convert the
2882/// expression From to bool (C++0x [conv]p3).
2883ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002884 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002885 // FIXME: Are these flags correct?
2886 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002887 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002888 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002889}
2890
2891/// PerformContextuallyConvertToBool - Perform a contextual conversion
2892/// of the expression From to bool (C++0x [conv]p3).
2893bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2894 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002895 if (!ICS.isBad())
2896 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002897
Fariborz Jahanian76197412009-11-18 18:26:29 +00002898 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002899 return Diag(From->getSourceRange().getBegin(),
2900 diag::err_typecheck_bool_condition)
2901 << From->getType() << From->getSourceRange();
2902 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002903}
2904
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002905/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002906/// candidate functions, using the given function call arguments. If
2907/// @p SuppressUserConversions, then don't allow user-defined
2908/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002909///
2910/// \para PartialOverloading true if we are performing "partial" overloading
2911/// based on an incomplete set of function arguments. This feature is used by
2912/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002913void
2914Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002915 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002916 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002917 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002918 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002919 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002920 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002921 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002922 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002923 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002924 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002925
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002926 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002927 if (!isa<CXXConstructorDecl>(Method)) {
2928 // If we get here, it's because we're calling a member function
2929 // that is named without a member access expression (e.g.,
2930 // "this->f") that was either written explicitly or created
2931 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002932 // function, e.g., X::f(). We use an empty type for the implied
2933 // object argument (C++ [over.call.func]p3), and the acting context
2934 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002935 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002936 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002937 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002938 return;
2939 }
2940 // We treat a constructor like a non-member function, since its object
2941 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002942 }
2943
Douglas Gregorff7028a2009-11-13 23:59:09 +00002944 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002945 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002946
Douglas Gregor27381f32009-11-23 12:27:39 +00002947 // Overload resolution is always an unevaluated context.
2948 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2949
Douglas Gregorffe14e32009-11-14 01:20:54 +00002950 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2951 // C++ [class.copy]p3:
2952 // A member function template is never instantiated to perform the copy
2953 // of a class object to an object of its class type.
2954 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2955 if (NumArgs == 1 &&
2956 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002957 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2958 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002959 return;
2960 }
2961
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002962 // Add this candidate
2963 CandidateSet.push_back(OverloadCandidate());
2964 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002965 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002966 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002967 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002968 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002969 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002970
2971 unsigned NumArgsInProto = Proto->getNumArgs();
2972
2973 // (C++ 13.3.2p2): A candidate function having fewer than m
2974 // parameters is viable only if it has an ellipsis in its parameter
2975 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002976 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2977 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002978 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002979 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002980 return;
2981 }
2982
2983 // (C++ 13.3.2p2): A candidate function having more than m parameters
2984 // is viable only if the (m+1)st parameter has a default argument
2985 // (8.3.6). For the purposes of overload resolution, the
2986 // parameter list is truncated on the right, so that there are
2987 // exactly m parameters.
2988 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002989 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002990 // Not enough arguments.
2991 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002992 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002993 return;
2994 }
2995
2996 // Determine the implicit conversion sequences for each of the
2997 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002998 Candidate.Conversions.resize(NumArgs);
2999 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3000 if (ArgIdx < NumArgsInProto) {
3001 // (C++ 13.3.2p3): for F to be a viable function, there shall
3002 // exist for each argument an implicit conversion sequence
3003 // (13.3.3.1) that converts that argument to the corresponding
3004 // parameter of F.
3005 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003006 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003007 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003008 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003009 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003010 if (Candidate.Conversions[ArgIdx].isBad()) {
3011 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003012 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003013 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003014 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003015 } else {
3016 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3017 // argument for which there is no corresponding parameter is
3018 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003019 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003020 }
3021 }
3022}
3023
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003024/// \brief Add all of the function declarations in the given function set to
3025/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003026void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003027 Expr **Args, unsigned NumArgs,
3028 OverloadCandidateSet& CandidateSet,
3029 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003030 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003031 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3032 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003033 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003034 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003035 cast<CXXMethodDecl>(FD)->getParent(),
3036 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003037 CandidateSet, SuppressUserConversions);
3038 else
John McCalla0296f72010-03-19 07:35:19 +00003039 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003040 SuppressUserConversions);
3041 } else {
John McCalla0296f72010-03-19 07:35:19 +00003042 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003043 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3044 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003045 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003046 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003047 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003048 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003049 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003050 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003051 else
John McCalla0296f72010-03-19 07:35:19 +00003052 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003053 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003054 Args, NumArgs, CandidateSet,
3055 SuppressUserConversions);
3056 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003057 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003058}
3059
John McCallf0f1cf02009-11-17 07:50:12 +00003060/// AddMethodCandidate - Adds a named decl (which is some kind of
3061/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003062void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003063 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003064 Expr **Args, unsigned NumArgs,
3065 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003066 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003067 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003068 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003069
3070 if (isa<UsingShadowDecl>(Decl))
3071 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3072
3073 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3074 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3075 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003076 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3077 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003078 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003079 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003080 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003081 } else {
John McCalla0296f72010-03-19 07:35:19 +00003082 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003083 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003084 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003085 }
3086}
3087
Douglas Gregor436424c2008-11-18 23:14:02 +00003088/// AddMethodCandidate - Adds the given C++ member function to the set
3089/// of candidate functions, using the given function call arguments
3090/// and the object argument (@c Object). For example, in a call
3091/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3092/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3093/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003094/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003095void
John McCalla0296f72010-03-19 07:35:19 +00003096Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003097 CXXRecordDecl *ActingContext, QualType ObjectType,
3098 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003099 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003100 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003101 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003102 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003103 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003104 assert(!isa<CXXConstructorDecl>(Method) &&
3105 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003106
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003107 if (!CandidateSet.isNewCandidate(Method))
3108 return;
3109
Douglas Gregor27381f32009-11-23 12:27:39 +00003110 // Overload resolution is always an unevaluated context.
3111 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3112
Douglas Gregor436424c2008-11-18 23:14:02 +00003113 // Add this candidate
3114 CandidateSet.push_back(OverloadCandidate());
3115 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003116 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003117 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003118 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003119 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003120
3121 unsigned NumArgsInProto = Proto->getNumArgs();
3122
3123 // (C++ 13.3.2p2): A candidate function having fewer than m
3124 // parameters is viable only if it has an ellipsis in its parameter
3125 // list (8.3.5).
3126 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3127 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003128 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003129 return;
3130 }
3131
3132 // (C++ 13.3.2p2): A candidate function having more than m parameters
3133 // is viable only if the (m+1)st parameter has a default argument
3134 // (8.3.6). For the purposes of overload resolution, the
3135 // parameter list is truncated on the right, so that there are
3136 // exactly m parameters.
3137 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3138 if (NumArgs < MinRequiredArgs) {
3139 // Not enough arguments.
3140 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003141 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003142 return;
3143 }
3144
3145 Candidate.Viable = true;
3146 Candidate.Conversions.resize(NumArgs + 1);
3147
John McCall6e9f8f62009-12-03 04:06:58 +00003148 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003149 // The implicit object argument is ignored.
3150 Candidate.IgnoreObjectArgument = true;
3151 else {
3152 // Determine the implicit conversion sequence for the object
3153 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003154 Candidate.Conversions[0]
3155 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003156 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003157 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003158 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003159 return;
3160 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003161 }
3162
3163 // Determine the implicit conversion sequences for each of the
3164 // arguments.
3165 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3166 if (ArgIdx < NumArgsInProto) {
3167 // (C++ 13.3.2p3): for F to be a viable function, there shall
3168 // exist for each argument an implicit conversion sequence
3169 // (13.3.3.1) that converts that argument to the corresponding
3170 // parameter of F.
3171 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003172 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003173 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003174 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003175 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003176 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003177 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003178 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003179 break;
3180 }
3181 } else {
3182 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3183 // argument for which there is no corresponding parameter is
3184 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003185 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003186 }
3187 }
3188}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003189
Douglas Gregor97628d62009-08-21 00:16:32 +00003190/// \brief Add a C++ member function template as a candidate to the candidate
3191/// set, using template argument deduction to produce an appropriate member
3192/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003193void
Douglas Gregor97628d62009-08-21 00:16:32 +00003194Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003195 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003196 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003197 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003198 QualType ObjectType,
3199 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003200 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003201 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003202 if (!CandidateSet.isNewCandidate(MethodTmpl))
3203 return;
3204
Douglas Gregor97628d62009-08-21 00:16:32 +00003205 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003206 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003207 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003208 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003209 // candidate functions in the usual way.113) A given name can refer to one
3210 // or more function templates and also to a set of overloaded non-template
3211 // functions. In such a case, the candidate functions generated from each
3212 // function template are combined with the set of non-template candidate
3213 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003214 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003215 FunctionDecl *Specialization = 0;
3216 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003217 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003218 Args, NumArgs, Specialization, Info)) {
3219 // FIXME: Record what happened with template argument deduction, so
3220 // that we can give the user a beautiful diagnostic.
3221 (void)Result;
3222 return;
3223 }
Mike Stump11289f42009-09-09 15:08:12 +00003224
Douglas Gregor97628d62009-08-21 00:16:32 +00003225 // Add the function template specialization produced by template argument
3226 // deduction as a candidate.
3227 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003228 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003229 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003230 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003231 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003232 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003233}
3234
Douglas Gregor05155d82009-08-21 23:19:43 +00003235/// \brief Add a C++ function template specialization as a candidate
3236/// in the candidate set, using template argument deduction to produce
3237/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003238void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003239Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003240 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003241 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003242 Expr **Args, unsigned NumArgs,
3243 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003244 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003245 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3246 return;
3247
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003248 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003249 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003250 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003251 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003252 // candidate functions in the usual way.113) A given name can refer to one
3253 // or more function templates and also to a set of overloaded non-template
3254 // functions. In such a case, the candidate functions generated from each
3255 // function template are combined with the set of non-template candidate
3256 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003257 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003258 FunctionDecl *Specialization = 0;
3259 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003260 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003261 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003262 CandidateSet.push_back(OverloadCandidate());
3263 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003264 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003265 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3266 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003267 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003268 Candidate.IsSurrogate = false;
3269 Candidate.IgnoreObjectArgument = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003270 Candidate.DeductionFailure = MakeDeductionFailureInfo(Result, Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003271 return;
3272 }
Mike Stump11289f42009-09-09 15:08:12 +00003273
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003274 // Add the function template specialization produced by template argument
3275 // deduction as a candidate.
3276 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003277 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003278 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003279}
Mike Stump11289f42009-09-09 15:08:12 +00003280
Douglas Gregora1f013e2008-11-07 22:36:19 +00003281/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003282/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003283/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003284/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003285/// (which may or may not be the same type as the type that the
3286/// conversion function produces).
3287void
3288Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003289 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003290 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003291 Expr *From, QualType ToType,
3292 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003293 assert(!Conversion->getDescribedFunctionTemplate() &&
3294 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003295 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003296 if (!CandidateSet.isNewCandidate(Conversion))
3297 return;
3298
Douglas Gregor27381f32009-11-23 12:27:39 +00003299 // Overload resolution is always an unevaluated context.
3300 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3301
Douglas Gregora1f013e2008-11-07 22:36:19 +00003302 // Add this candidate
3303 CandidateSet.push_back(OverloadCandidate());
3304 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003305 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003306 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003307 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003308 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003309 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003310 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003311 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003312
Douglas Gregor436424c2008-11-18 23:14:02 +00003313 // Determine the implicit conversion sequence for the implicit
3314 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003315 Candidate.Viable = true;
3316 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003317 Candidate.Conversions[0]
3318 = TryObjectArgumentInitialization(From->getType(), Conversion,
3319 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003320 // Conversion functions to a different type in the base class is visible in
3321 // the derived class. So, a derived to base conversion should not participate
3322 // in overload resolution.
3323 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3324 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003325 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003326 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003327 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003328 return;
3329 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003330
3331 // We won't go through a user-define type conversion function to convert a
3332 // derived to base as such conversions are given Conversion Rank. They only
3333 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3334 QualType FromCanon
3335 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3336 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3337 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3338 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003339 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003340 return;
3341 }
3342
Douglas Gregora1f013e2008-11-07 22:36:19 +00003343 // To determine what the conversion from the result of calling the
3344 // conversion function to the type we're eventually trying to
3345 // convert to (ToType), we need to synthesize a call to the
3346 // conversion function and attempt copy initialization from it. This
3347 // makes sure that we get the right semantics with respect to
3348 // lvalues/rvalues and the type. Fortunately, we can allocate this
3349 // call on the stack and we don't need its arguments to be
3350 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003351 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003352 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003353 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003354 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003355 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003356
3357 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003358 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3359 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003360 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003361 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003362 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003363 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003364 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003365 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003366 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003367
John McCall0d1da222010-01-12 00:44:57 +00003368 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003369 case ImplicitConversionSequence::StandardConversion:
3370 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003371
3372 // C++ [over.ics.user]p3:
3373 // If the user-defined conversion is specified by a specialization of a
3374 // conversion function template, the second standard conversion sequence
3375 // shall have exact match rank.
3376 if (Conversion->getPrimaryTemplate() &&
3377 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3378 Candidate.Viable = false;
3379 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3380 }
3381
Douglas Gregora1f013e2008-11-07 22:36:19 +00003382 break;
3383
3384 case ImplicitConversionSequence::BadConversion:
3385 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003386 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003387 break;
3388
3389 default:
Mike Stump11289f42009-09-09 15:08:12 +00003390 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003391 "Can only end up with a standard conversion sequence or failure");
3392 }
3393}
3394
Douglas Gregor05155d82009-08-21 23:19:43 +00003395/// \brief Adds a conversion function template specialization
3396/// candidate to the overload set, using template argument deduction
3397/// to deduce the template arguments of the conversion function
3398/// template from the type that we are converting to (C++
3399/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003400void
Douglas Gregor05155d82009-08-21 23:19:43 +00003401Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003402 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003403 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003404 Expr *From, QualType ToType,
3405 OverloadCandidateSet &CandidateSet) {
3406 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3407 "Only conversion function templates permitted here");
3408
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003409 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3410 return;
3411
John McCallbc077cf2010-02-08 23:07:23 +00003412 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003413 CXXConversionDecl *Specialization = 0;
3414 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003415 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003416 Specialization, Info)) {
3417 // FIXME: Record what happened with template argument deduction, so
3418 // that we can give the user a beautiful diagnostic.
3419 (void)Result;
3420 return;
3421 }
Mike Stump11289f42009-09-09 15:08:12 +00003422
Douglas Gregor05155d82009-08-21 23:19:43 +00003423 // Add the conversion function template specialization produced by
3424 // template argument deduction as a candidate.
3425 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003426 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003427 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003428}
3429
Douglas Gregorab7897a2008-11-19 22:57:39 +00003430/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3431/// converts the given @c Object to a function pointer via the
3432/// conversion function @c Conversion, and then attempts to call it
3433/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3434/// the type of function that we'll eventually be calling.
3435void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003436 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003437 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003438 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003439 QualType ObjectType,
3440 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003441 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003442 if (!CandidateSet.isNewCandidate(Conversion))
3443 return;
3444
Douglas Gregor27381f32009-11-23 12:27:39 +00003445 // Overload resolution is always an unevaluated context.
3446 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3447
Douglas Gregorab7897a2008-11-19 22:57:39 +00003448 CandidateSet.push_back(OverloadCandidate());
3449 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003450 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003451 Candidate.Function = 0;
3452 Candidate.Surrogate = Conversion;
3453 Candidate.Viable = true;
3454 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003455 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003456 Candidate.Conversions.resize(NumArgs + 1);
3457
3458 // Determine the implicit conversion sequence for the implicit
3459 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003460 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003461 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003462 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003463 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003464 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003465 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003466 return;
3467 }
3468
3469 // The first conversion is actually a user-defined conversion whose
3470 // first conversion is ObjectInit's standard conversion (which is
3471 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003472 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003473 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003474 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003475 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003476 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003477 = Candidate.Conversions[0].UserDefined.Before;
3478 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3479
Mike Stump11289f42009-09-09 15:08:12 +00003480 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003481 unsigned NumArgsInProto = Proto->getNumArgs();
3482
3483 // (C++ 13.3.2p2): A candidate function having fewer than m
3484 // parameters is viable only if it has an ellipsis in its parameter
3485 // list (8.3.5).
3486 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3487 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003488 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003489 return;
3490 }
3491
3492 // Function types don't have any default arguments, so just check if
3493 // we have enough arguments.
3494 if (NumArgs < NumArgsInProto) {
3495 // Not enough arguments.
3496 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003497 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003498 return;
3499 }
3500
3501 // Determine the implicit conversion sequences for each of the
3502 // arguments.
3503 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3504 if (ArgIdx < NumArgsInProto) {
3505 // (C++ 13.3.2p3): for F to be a viable function, there shall
3506 // exist for each argument an implicit conversion sequence
3507 // (13.3.3.1) that converts that argument to the corresponding
3508 // parameter of F.
3509 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003510 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003511 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003512 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003513 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003514 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003515 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003516 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003517 break;
3518 }
3519 } else {
3520 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3521 // argument for which there is no corresponding parameter is
3522 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003523 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003524 }
3525 }
3526}
3527
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003528/// \brief Add overload candidates for overloaded operators that are
3529/// member functions.
3530///
3531/// Add the overloaded operator candidates that are member functions
3532/// for the operator Op that was used in an operator expression such
3533/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3534/// CandidateSet will store the added overload candidates. (C++
3535/// [over.match.oper]).
3536void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3537 SourceLocation OpLoc,
3538 Expr **Args, unsigned NumArgs,
3539 OverloadCandidateSet& CandidateSet,
3540 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003541 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3542
3543 // C++ [over.match.oper]p3:
3544 // For a unary operator @ with an operand of a type whose
3545 // cv-unqualified version is T1, and for a binary operator @ with
3546 // a left operand of a type whose cv-unqualified version is T1 and
3547 // a right operand of a type whose cv-unqualified version is T2,
3548 // three sets of candidate functions, designated member
3549 // candidates, non-member candidates and built-in candidates, are
3550 // constructed as follows:
3551 QualType T1 = Args[0]->getType();
3552 QualType T2;
3553 if (NumArgs > 1)
3554 T2 = Args[1]->getType();
3555
3556 // -- If T1 is a class type, the set of member candidates is the
3557 // result of the qualified lookup of T1::operator@
3558 // (13.3.1.1.1); otherwise, the set of member candidates is
3559 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003560 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003561 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003562 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003563 return;
Mike Stump11289f42009-09-09 15:08:12 +00003564
John McCall27b18f82009-11-17 02:14:36 +00003565 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3566 LookupQualifiedName(Operators, T1Rec->getDecl());
3567 Operators.suppressDiagnostics();
3568
Mike Stump11289f42009-09-09 15:08:12 +00003569 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003570 OperEnd = Operators.end();
3571 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003572 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003573 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003574 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003575 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003576 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003577}
3578
Douglas Gregora11693b2008-11-12 17:17:38 +00003579/// AddBuiltinCandidate - Add a candidate for a built-in
3580/// operator. ResultTy and ParamTys are the result and parameter types
3581/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003582/// arguments being passed to the candidate. IsAssignmentOperator
3583/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003584/// operator. NumContextualBoolArguments is the number of arguments
3585/// (at the beginning of the argument list) that will be contextually
3586/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003587void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003588 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003589 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003590 bool IsAssignmentOperator,
3591 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003592 // Overload resolution is always an unevaluated context.
3593 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3594
Douglas Gregora11693b2008-11-12 17:17:38 +00003595 // Add this candidate
3596 CandidateSet.push_back(OverloadCandidate());
3597 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003598 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003599 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003600 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003601 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003602 Candidate.BuiltinTypes.ResultTy = ResultTy;
3603 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3604 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3605
3606 // Determine the implicit conversion sequences for each of the
3607 // arguments.
3608 Candidate.Viable = true;
3609 Candidate.Conversions.resize(NumArgs);
3610 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003611 // C++ [over.match.oper]p4:
3612 // For the built-in assignment operators, conversions of the
3613 // left operand are restricted as follows:
3614 // -- no temporaries are introduced to hold the left operand, and
3615 // -- no user-defined conversions are applied to the left
3616 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003617 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003618 //
3619 // We block these conversions by turning off user-defined
3620 // conversions, since that is the only way that initialization of
3621 // a reference to a non-class type can occur from something that
3622 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003623 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003624 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003625 "Contextual conversion to bool requires bool type");
3626 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3627 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003628 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003629 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003630 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003631 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003632 }
John McCall0d1da222010-01-12 00:44:57 +00003633 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003634 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003635 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003636 break;
3637 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003638 }
3639}
3640
3641/// BuiltinCandidateTypeSet - A set of types that will be used for the
3642/// candidate operator functions for built-in operators (C++
3643/// [over.built]). The types are separated into pointer types and
3644/// enumeration types.
3645class BuiltinCandidateTypeSet {
3646 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003647 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003648
3649 /// PointerTypes - The set of pointer types that will be used in the
3650 /// built-in candidates.
3651 TypeSet PointerTypes;
3652
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003653 /// MemberPointerTypes - The set of member pointer types that will be
3654 /// used in the built-in candidates.
3655 TypeSet MemberPointerTypes;
3656
Douglas Gregora11693b2008-11-12 17:17:38 +00003657 /// EnumerationTypes - The set of enumeration types that will be
3658 /// used in the built-in candidates.
3659 TypeSet EnumerationTypes;
3660
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003661 /// Sema - The semantic analysis instance where we are building the
3662 /// candidate type set.
3663 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003664
Douglas Gregora11693b2008-11-12 17:17:38 +00003665 /// Context - The AST context in which we will build the type sets.
3666 ASTContext &Context;
3667
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003668 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3669 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003670 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003671
3672public:
3673 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003674 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003675
Mike Stump11289f42009-09-09 15:08:12 +00003676 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003677 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003678
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003679 void AddTypesConvertedFrom(QualType Ty,
3680 SourceLocation Loc,
3681 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003682 bool AllowExplicitConversions,
3683 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003684
3685 /// pointer_begin - First pointer type found;
3686 iterator pointer_begin() { return PointerTypes.begin(); }
3687
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003688 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003689 iterator pointer_end() { return PointerTypes.end(); }
3690
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003691 /// member_pointer_begin - First member pointer type found;
3692 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3693
3694 /// member_pointer_end - Past the last member pointer type found;
3695 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3696
Douglas Gregora11693b2008-11-12 17:17:38 +00003697 /// enumeration_begin - First enumeration type found;
3698 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3699
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003700 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003701 iterator enumeration_end() { return EnumerationTypes.end(); }
3702};
3703
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003704/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003705/// the set of pointer types along with any more-qualified variants of
3706/// that type. For example, if @p Ty is "int const *", this routine
3707/// will add "int const *", "int const volatile *", "int const
3708/// restrict *", and "int const volatile restrict *" to the set of
3709/// pointer types. Returns true if the add of @p Ty itself succeeded,
3710/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003711///
3712/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003713bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003714BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3715 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003716
Douglas Gregora11693b2008-11-12 17:17:38 +00003717 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003718 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003719 return false;
3720
John McCall8ccfcb52009-09-24 19:53:00 +00003721 const PointerType *PointerTy = Ty->getAs<PointerType>();
3722 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003723
John McCall8ccfcb52009-09-24 19:53:00 +00003724 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003725 // Don't add qualified variants of arrays. For one, they're not allowed
3726 // (the qualifier would sink to the element type), and for another, the
3727 // only overload situation where it matters is subscript or pointer +- int,
3728 // and those shouldn't have qualifier variants anyway.
3729 if (PointeeTy->isArrayType())
3730 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003731 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003732 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003733 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003734 bool hasVolatile = VisibleQuals.hasVolatile();
3735 bool hasRestrict = VisibleQuals.hasRestrict();
3736
John McCall8ccfcb52009-09-24 19:53:00 +00003737 // Iterate through all strict supersets of BaseCVR.
3738 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3739 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003740 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3741 // in the types.
3742 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3743 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003744 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3745 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003746 }
3747
3748 return true;
3749}
3750
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003751/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3752/// to the set of pointer types along with any more-qualified variants of
3753/// that type. For example, if @p Ty is "int const *", this routine
3754/// will add "int const *", "int const volatile *", "int const
3755/// restrict *", and "int const volatile restrict *" to the set of
3756/// pointer types. Returns true if the add of @p Ty itself succeeded,
3757/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003758///
3759/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003760bool
3761BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3762 QualType Ty) {
3763 // Insert this type.
3764 if (!MemberPointerTypes.insert(Ty))
3765 return false;
3766
John McCall8ccfcb52009-09-24 19:53:00 +00003767 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3768 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003769
John McCall8ccfcb52009-09-24 19:53:00 +00003770 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003771 // Don't add qualified variants of arrays. For one, they're not allowed
3772 // (the qualifier would sink to the element type), and for another, the
3773 // only overload situation where it matters is subscript or pointer +- int,
3774 // and those shouldn't have qualifier variants anyway.
3775 if (PointeeTy->isArrayType())
3776 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003777 const Type *ClassTy = PointerTy->getClass();
3778
3779 // Iterate through all strict supersets of the pointee type's CVR
3780 // qualifiers.
3781 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3782 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3783 if ((CVR | BaseCVR) != CVR) continue;
3784
3785 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3786 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003787 }
3788
3789 return true;
3790}
3791
Douglas Gregora11693b2008-11-12 17:17:38 +00003792/// AddTypesConvertedFrom - Add each of the types to which the type @p
3793/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003794/// primarily interested in pointer types and enumeration types. We also
3795/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003796/// AllowUserConversions is true if we should look at the conversion
3797/// functions of a class type, and AllowExplicitConversions if we
3798/// should also include the explicit conversion functions of a class
3799/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003800void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003801BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003802 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003803 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003804 bool AllowExplicitConversions,
3805 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003806 // Only deal with canonical types.
3807 Ty = Context.getCanonicalType(Ty);
3808
3809 // Look through reference types; they aren't part of the type of an
3810 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003811 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003812 Ty = RefTy->getPointeeType();
3813
3814 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003815 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003816
Sebastian Redl65ae2002009-11-05 16:36:20 +00003817 // If we're dealing with an array type, decay to the pointer.
3818 if (Ty->isArrayType())
3819 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3820
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003821 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003822 QualType PointeeTy = PointerTy->getPointeeType();
3823
3824 // Insert our type, and its more-qualified variants, into the set
3825 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003826 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003827 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003828 } else if (Ty->isMemberPointerType()) {
3829 // Member pointers are far easier, since the pointee can't be converted.
3830 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3831 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003832 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003833 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003834 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003835 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003836 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003837 // No conversion functions in incomplete types.
3838 return;
3839 }
Mike Stump11289f42009-09-09 15:08:12 +00003840
Douglas Gregora11693b2008-11-12 17:17:38 +00003841 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003842 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003843 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003844 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003845 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003846 NamedDecl *D = I.getDecl();
3847 if (isa<UsingShadowDecl>(D))
3848 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003849
Mike Stump11289f42009-09-09 15:08:12 +00003850 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003851 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003852 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003853 continue;
3854
John McCallda4458e2010-03-31 01:36:47 +00003855 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003856 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003857 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003858 VisibleQuals);
3859 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003860 }
3861 }
3862 }
3863}
3864
Douglas Gregor84605ae2009-08-24 13:43:27 +00003865/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3866/// the volatile- and non-volatile-qualified assignment operators for the
3867/// given type to the candidate set.
3868static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3869 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003870 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003871 unsigned NumArgs,
3872 OverloadCandidateSet &CandidateSet) {
3873 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003874
Douglas Gregor84605ae2009-08-24 13:43:27 +00003875 // T& operator=(T&, T)
3876 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3877 ParamTypes[1] = T;
3878 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3879 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003880
Douglas Gregor84605ae2009-08-24 13:43:27 +00003881 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3882 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003883 ParamTypes[0]
3884 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003885 ParamTypes[1] = T;
3886 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003887 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003888 }
3889}
Mike Stump11289f42009-09-09 15:08:12 +00003890
Sebastian Redl1054fae2009-10-25 17:03:50 +00003891/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3892/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003893static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3894 Qualifiers VRQuals;
3895 const RecordType *TyRec;
3896 if (const MemberPointerType *RHSMPType =
3897 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00003898 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003899 else
3900 TyRec = ArgExpr->getType()->getAs<RecordType>();
3901 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003902 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003903 VRQuals.addVolatile();
3904 VRQuals.addRestrict();
3905 return VRQuals;
3906 }
3907
3908 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003909 if (!ClassDecl->hasDefinition())
3910 return VRQuals;
3911
John McCallad371252010-01-20 00:46:10 +00003912 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003913 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003914
John McCallad371252010-01-20 00:46:10 +00003915 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003916 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003917 NamedDecl *D = I.getDecl();
3918 if (isa<UsingShadowDecl>(D))
3919 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3920 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003921 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3922 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3923 CanTy = ResTypeRef->getPointeeType();
3924 // Need to go down the pointer/mempointer chain and add qualifiers
3925 // as see them.
3926 bool done = false;
3927 while (!done) {
3928 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3929 CanTy = ResTypePtr->getPointeeType();
3930 else if (const MemberPointerType *ResTypeMPtr =
3931 CanTy->getAs<MemberPointerType>())
3932 CanTy = ResTypeMPtr->getPointeeType();
3933 else
3934 done = true;
3935 if (CanTy.isVolatileQualified())
3936 VRQuals.addVolatile();
3937 if (CanTy.isRestrictQualified())
3938 VRQuals.addRestrict();
3939 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3940 return VRQuals;
3941 }
3942 }
3943 }
3944 return VRQuals;
3945}
3946
Douglas Gregord08452f2008-11-19 15:42:04 +00003947/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3948/// operator overloads to the candidate set (C++ [over.built]), based
3949/// on the operator @p Op and the arguments given. For example, if the
3950/// operator is a binary '+', this routine might add "int
3951/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003952void
Mike Stump11289f42009-09-09 15:08:12 +00003953Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003954 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003955 Expr **Args, unsigned NumArgs,
3956 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003957 // The set of "promoted arithmetic types", which are the arithmetic
3958 // types are that preserved by promotion (C++ [over.built]p2). Note
3959 // that the first few of these types are the promoted integral
3960 // types; these types need to be first.
3961 // FIXME: What about complex?
3962 const unsigned FirstIntegralType = 0;
3963 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003964 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003965 LastPromotedIntegralType = 13;
3966 const unsigned FirstPromotedArithmeticType = 7,
3967 LastPromotedArithmeticType = 16;
3968 const unsigned NumArithmeticTypes = 16;
3969 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003970 Context.BoolTy, Context.CharTy, Context.WCharTy,
3971// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003972 Context.SignedCharTy, Context.ShortTy,
3973 Context.UnsignedCharTy, Context.UnsignedShortTy,
3974 Context.IntTy, Context.LongTy, Context.LongLongTy,
3975 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3976 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3977 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003978 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3979 "Invalid first promoted integral type");
3980 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3981 == Context.UnsignedLongLongTy &&
3982 "Invalid last promoted integral type");
3983 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3984 "Invalid first promoted arithmetic type");
3985 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3986 == Context.LongDoubleTy &&
3987 "Invalid last promoted arithmetic type");
3988
Douglas Gregora11693b2008-11-12 17:17:38 +00003989 // Find all of the types that the arguments can convert to, but only
3990 // if the operator we're looking at has built-in operator candidates
3991 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003992 Qualifiers VisibleTypeConversionsQuals;
3993 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003994 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3995 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3996
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003997 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003998 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3999 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00004000 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00004001 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00004002 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00004003 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004004 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00004005 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004006 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004007 true,
4008 (Op == OO_Exclaim ||
4009 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004010 Op == OO_PipePipe),
4011 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004012 }
4013
4014 bool isComparison = false;
4015 switch (Op) {
4016 case OO_None:
4017 case NUM_OVERLOADED_OPERATORS:
4018 assert(false && "Expected an overloaded operator");
4019 break;
4020
Douglas Gregord08452f2008-11-19 15:42:04 +00004021 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004022 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004023 goto UnaryStar;
4024 else
4025 goto BinaryStar;
4026 break;
4027
4028 case OO_Plus: // '+' is either unary or binary
4029 if (NumArgs == 1)
4030 goto UnaryPlus;
4031 else
4032 goto BinaryPlus;
4033 break;
4034
4035 case OO_Minus: // '-' is either unary or binary
4036 if (NumArgs == 1)
4037 goto UnaryMinus;
4038 else
4039 goto BinaryMinus;
4040 break;
4041
4042 case OO_Amp: // '&' is either unary or binary
4043 if (NumArgs == 1)
4044 goto UnaryAmp;
4045 else
4046 goto BinaryAmp;
4047
4048 case OO_PlusPlus:
4049 case OO_MinusMinus:
4050 // C++ [over.built]p3:
4051 //
4052 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4053 // is either volatile or empty, there exist candidate operator
4054 // functions of the form
4055 //
4056 // VQ T& operator++(VQ T&);
4057 // T operator++(VQ T&, int);
4058 //
4059 // C++ [over.built]p4:
4060 //
4061 // For every pair (T, VQ), where T is an arithmetic type other
4062 // than bool, and VQ is either volatile or empty, there exist
4063 // candidate operator functions of the form
4064 //
4065 // VQ T& operator--(VQ T&);
4066 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004067 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004068 Arith < NumArithmeticTypes; ++Arith) {
4069 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004070 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004071 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004072
4073 // Non-volatile version.
4074 if (NumArgs == 1)
4075 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4076 else
4077 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004078 // heuristic to reduce number of builtin candidates in the set.
4079 // Add volatile version only if there are conversions to a volatile type.
4080 if (VisibleTypeConversionsQuals.hasVolatile()) {
4081 // Volatile version
4082 ParamTypes[0]
4083 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4084 if (NumArgs == 1)
4085 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4086 else
4087 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4088 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004089 }
4090
4091 // C++ [over.built]p5:
4092 //
4093 // For every pair (T, VQ), where T is a cv-qualified or
4094 // cv-unqualified object type, and VQ is either volatile or
4095 // empty, there exist candidate operator functions of the form
4096 //
4097 // T*VQ& operator++(T*VQ&);
4098 // T*VQ& operator--(T*VQ&);
4099 // T* operator++(T*VQ&, int);
4100 // T* operator--(T*VQ&, int);
4101 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4102 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4103 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004104 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004105 continue;
4106
Mike Stump11289f42009-09-09 15:08:12 +00004107 QualType ParamTypes[2] = {
4108 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004109 };
Mike Stump11289f42009-09-09 15:08:12 +00004110
Douglas Gregord08452f2008-11-19 15:42:04 +00004111 // Without volatile
4112 if (NumArgs == 1)
4113 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4114 else
4115 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4116
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004117 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4118 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004119 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004120 ParamTypes[0]
4121 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004122 if (NumArgs == 1)
4123 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4124 else
4125 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4126 }
4127 }
4128 break;
4129
4130 UnaryStar:
4131 // C++ [over.built]p6:
4132 // For every cv-qualified or cv-unqualified object type T, there
4133 // exist candidate operator functions of the form
4134 //
4135 // T& operator*(T*);
4136 //
4137 // C++ [over.built]p7:
4138 // For every function type T, there exist candidate operator
4139 // functions of the form
4140 // T& operator*(T*);
4141 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4142 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4143 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004144 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004145 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004146 &ParamTy, Args, 1, CandidateSet);
4147 }
4148 break;
4149
4150 UnaryPlus:
4151 // C++ [over.built]p8:
4152 // For every type T, there exist candidate operator functions of
4153 // the form
4154 //
4155 // T* operator+(T*);
4156 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4157 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4158 QualType ParamTy = *Ptr;
4159 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4160 }
Mike Stump11289f42009-09-09 15:08:12 +00004161
Douglas Gregord08452f2008-11-19 15:42:04 +00004162 // Fall through
4163
4164 UnaryMinus:
4165 // C++ [over.built]p9:
4166 // For every promoted arithmetic type T, there exist candidate
4167 // operator functions of the form
4168 //
4169 // T operator+(T);
4170 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004171 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004172 Arith < LastPromotedArithmeticType; ++Arith) {
4173 QualType ArithTy = ArithmeticTypes[Arith];
4174 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4175 }
4176 break;
4177
4178 case OO_Tilde:
4179 // C++ [over.built]p10:
4180 // For every promoted integral type T, there exist candidate
4181 // operator functions of the form
4182 //
4183 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004184 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004185 Int < LastPromotedIntegralType; ++Int) {
4186 QualType IntTy = ArithmeticTypes[Int];
4187 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4188 }
4189 break;
4190
Douglas Gregora11693b2008-11-12 17:17:38 +00004191 case OO_New:
4192 case OO_Delete:
4193 case OO_Array_New:
4194 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004195 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004196 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004197 break;
4198
4199 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004200 UnaryAmp:
4201 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004202 // C++ [over.match.oper]p3:
4203 // -- For the operator ',', the unary operator '&', or the
4204 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004205 break;
4206
Douglas Gregor84605ae2009-08-24 13:43:27 +00004207 case OO_EqualEqual:
4208 case OO_ExclaimEqual:
4209 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004210 // For every pointer to member type T, there exist candidate operator
4211 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004212 //
4213 // bool operator==(T,T);
4214 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004215 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004216 MemPtr = CandidateTypes.member_pointer_begin(),
4217 MemPtrEnd = CandidateTypes.member_pointer_end();
4218 MemPtr != MemPtrEnd;
4219 ++MemPtr) {
4220 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4221 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
Douglas Gregor84605ae2009-08-24 13:43:27 +00004224 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004225
Douglas Gregora11693b2008-11-12 17:17:38 +00004226 case OO_Less:
4227 case OO_Greater:
4228 case OO_LessEqual:
4229 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004230 // C++ [over.built]p15:
4231 //
4232 // For every pointer or enumeration type T, there exist
4233 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004234 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004235 // bool operator<(T, T);
4236 // bool operator>(T, T);
4237 // bool operator<=(T, T);
4238 // bool operator>=(T, T);
4239 // bool operator==(T, T);
4240 // bool operator!=(T, T);
4241 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4242 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4243 QualType ParamTypes[2] = { *Ptr, *Ptr };
4244 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4245 }
Mike Stump11289f42009-09-09 15:08:12 +00004246 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004247 = CandidateTypes.enumeration_begin();
4248 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4249 QualType ParamTypes[2] = { *Enum, *Enum };
4250 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4251 }
4252
4253 // Fall through.
4254 isComparison = true;
4255
Douglas Gregord08452f2008-11-19 15:42:04 +00004256 BinaryPlus:
4257 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004258 if (!isComparison) {
4259 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4260
4261 // C++ [over.built]p13:
4262 //
4263 // For every cv-qualified or cv-unqualified object type T
4264 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004265 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004266 // T* operator+(T*, ptrdiff_t);
4267 // T& operator[](T*, ptrdiff_t); [BELOW]
4268 // T* operator-(T*, ptrdiff_t);
4269 // T* operator+(ptrdiff_t, T*);
4270 // T& operator[](ptrdiff_t, T*); [BELOW]
4271 //
4272 // C++ [over.built]p14:
4273 //
4274 // For every T, where T is a pointer to object type, there
4275 // exist candidate operator functions of the form
4276 //
4277 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004278 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004279 = CandidateTypes.pointer_begin();
4280 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4281 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4282
4283 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4284 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4285
4286 if (Op == OO_Plus) {
4287 // T* operator+(ptrdiff_t, T*);
4288 ParamTypes[0] = ParamTypes[1];
4289 ParamTypes[1] = *Ptr;
4290 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4291 } else {
4292 // ptrdiff_t operator-(T, T);
4293 ParamTypes[1] = *Ptr;
4294 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4295 Args, 2, CandidateSet);
4296 }
4297 }
4298 }
4299 // Fall through
4300
Douglas Gregora11693b2008-11-12 17:17:38 +00004301 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004302 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004303 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004304 // C++ [over.built]p12:
4305 //
4306 // For every pair of promoted arithmetic types L and R, there
4307 // exist candidate operator functions of the form
4308 //
4309 // LR operator*(L, R);
4310 // LR operator/(L, R);
4311 // LR operator+(L, R);
4312 // LR operator-(L, R);
4313 // bool operator<(L, R);
4314 // bool operator>(L, R);
4315 // bool operator<=(L, R);
4316 // bool operator>=(L, R);
4317 // bool operator==(L, R);
4318 // bool operator!=(L, R);
4319 //
4320 // where LR is the result of the usual arithmetic conversions
4321 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004322 //
4323 // C++ [over.built]p24:
4324 //
4325 // For every pair of promoted arithmetic types L and R, there exist
4326 // candidate operator functions of the form
4327 //
4328 // LR operator?(bool, L, R);
4329 //
4330 // where LR is the result of the usual arithmetic conversions
4331 // between types L and R.
4332 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004333 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004334 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004335 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004336 Right < LastPromotedArithmeticType; ++Right) {
4337 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004338 QualType Result
4339 = isComparison
4340 ? Context.BoolTy
4341 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004342 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4343 }
4344 }
4345 break;
4346
4347 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004348 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004349 case OO_Caret:
4350 case OO_Pipe:
4351 case OO_LessLess:
4352 case OO_GreaterGreater:
4353 // C++ [over.built]p17:
4354 //
4355 // For every pair of promoted integral types L and R, there
4356 // exist candidate operator functions of the form
4357 //
4358 // LR operator%(L, R);
4359 // LR operator&(L, R);
4360 // LR operator^(L, R);
4361 // LR operator|(L, R);
4362 // L operator<<(L, R);
4363 // L operator>>(L, R);
4364 //
4365 // where LR is the result of the usual arithmetic conversions
4366 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004367 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004368 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004369 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004370 Right < LastPromotedIntegralType; ++Right) {
4371 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4372 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4373 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004374 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004375 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4376 }
4377 }
4378 break;
4379
4380 case OO_Equal:
4381 // C++ [over.built]p20:
4382 //
4383 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004384 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004385 // empty, there exist candidate operator functions of the form
4386 //
4387 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004388 for (BuiltinCandidateTypeSet::iterator
4389 Enum = CandidateTypes.enumeration_begin(),
4390 EnumEnd = CandidateTypes.enumeration_end();
4391 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004392 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004393 CandidateSet);
4394 for (BuiltinCandidateTypeSet::iterator
4395 MemPtr = CandidateTypes.member_pointer_begin(),
4396 MemPtrEnd = CandidateTypes.member_pointer_end();
4397 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004398 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004399 CandidateSet);
4400 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004401
4402 case OO_PlusEqual:
4403 case OO_MinusEqual:
4404 // C++ [over.built]p19:
4405 //
4406 // For every pair (T, VQ), where T is any type and VQ is either
4407 // volatile or empty, there exist candidate operator functions
4408 // of the form
4409 //
4410 // T*VQ& operator=(T*VQ&, T*);
4411 //
4412 // C++ [over.built]p21:
4413 //
4414 // For every pair (T, VQ), where T is a cv-qualified or
4415 // cv-unqualified object type and VQ is either volatile or
4416 // empty, there exist candidate operator functions of the form
4417 //
4418 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4419 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4420 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4421 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4422 QualType ParamTypes[2];
4423 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4424
4425 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004426 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004427 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4428 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004429
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004430 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4431 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004432 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004433 ParamTypes[0]
4434 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004435 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4436 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004437 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004438 }
4439 // Fall through.
4440
4441 case OO_StarEqual:
4442 case OO_SlashEqual:
4443 // C++ [over.built]p18:
4444 //
4445 // For every triple (L, VQ, R), where L is an arithmetic type,
4446 // VQ is either volatile or empty, and R is a promoted
4447 // arithmetic type, there exist candidate operator functions of
4448 // the form
4449 //
4450 // VQ L& operator=(VQ L&, R);
4451 // VQ L& operator*=(VQ L&, R);
4452 // VQ L& operator/=(VQ L&, R);
4453 // VQ L& operator+=(VQ L&, R);
4454 // VQ L& operator-=(VQ L&, R);
4455 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004456 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004457 Right < LastPromotedArithmeticType; ++Right) {
4458 QualType ParamTypes[2];
4459 ParamTypes[1] = ArithmeticTypes[Right];
4460
4461 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004462 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004463 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4464 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004465
4466 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004467 if (VisibleTypeConversionsQuals.hasVolatile()) {
4468 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4469 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4470 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4471 /*IsAssigmentOperator=*/Op == OO_Equal);
4472 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004473 }
4474 }
4475 break;
4476
4477 case OO_PercentEqual:
4478 case OO_LessLessEqual:
4479 case OO_GreaterGreaterEqual:
4480 case OO_AmpEqual:
4481 case OO_CaretEqual:
4482 case OO_PipeEqual:
4483 // C++ [over.built]p22:
4484 //
4485 // For every triple (L, VQ, R), where L is an integral type, VQ
4486 // is either volatile or empty, and R is a promoted integral
4487 // type, there exist candidate operator functions of the form
4488 //
4489 // VQ L& operator%=(VQ L&, R);
4490 // VQ L& operator<<=(VQ L&, R);
4491 // VQ L& operator>>=(VQ L&, R);
4492 // VQ L& operator&=(VQ L&, R);
4493 // VQ L& operator^=(VQ L&, R);
4494 // VQ L& operator|=(VQ L&, R);
4495 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004496 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004497 Right < LastPromotedIntegralType; ++Right) {
4498 QualType ParamTypes[2];
4499 ParamTypes[1] = ArithmeticTypes[Right];
4500
4501 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004502 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004503 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004504 if (VisibleTypeConversionsQuals.hasVolatile()) {
4505 // Add this built-in operator as a candidate (VQ is 'volatile').
4506 ParamTypes[0] = ArithmeticTypes[Left];
4507 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4508 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4509 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4510 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004511 }
4512 }
4513 break;
4514
Douglas Gregord08452f2008-11-19 15:42:04 +00004515 case OO_Exclaim: {
4516 // C++ [over.operator]p23:
4517 //
4518 // There also exist candidate operator functions of the form
4519 //
Mike Stump11289f42009-09-09 15:08:12 +00004520 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004521 // bool operator&&(bool, bool); [BELOW]
4522 // bool operator||(bool, bool); [BELOW]
4523 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004524 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4525 /*IsAssignmentOperator=*/false,
4526 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004527 break;
4528 }
4529
Douglas Gregora11693b2008-11-12 17:17:38 +00004530 case OO_AmpAmp:
4531 case OO_PipePipe: {
4532 // C++ [over.operator]p23:
4533 //
4534 // There also exist candidate operator functions of the form
4535 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004536 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004537 // bool operator&&(bool, bool);
4538 // bool operator||(bool, bool);
4539 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004540 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4541 /*IsAssignmentOperator=*/false,
4542 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004543 break;
4544 }
4545
4546 case OO_Subscript:
4547 // C++ [over.built]p13:
4548 //
4549 // For every cv-qualified or cv-unqualified object type T there
4550 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004551 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004552 // T* operator+(T*, ptrdiff_t); [ABOVE]
4553 // T& operator[](T*, ptrdiff_t);
4554 // T* operator-(T*, ptrdiff_t); [ABOVE]
4555 // T* operator+(ptrdiff_t, T*); [ABOVE]
4556 // T& operator[](ptrdiff_t, T*);
4557 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4558 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4559 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004560 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004561 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004562
4563 // T& operator[](T*, ptrdiff_t)
4564 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4565
4566 // T& operator[](ptrdiff_t, T*);
4567 ParamTypes[0] = ParamTypes[1];
4568 ParamTypes[1] = *Ptr;
4569 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4570 }
4571 break;
4572
4573 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004574 // C++ [over.built]p11:
4575 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4576 // C1 is the same type as C2 or is a derived class of C2, T is an object
4577 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4578 // there exist candidate operator functions of the form
4579 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4580 // where CV12 is the union of CV1 and CV2.
4581 {
4582 for (BuiltinCandidateTypeSet::iterator Ptr =
4583 CandidateTypes.pointer_begin();
4584 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4585 QualType C1Ty = (*Ptr);
4586 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004587 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004588 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004589 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004590 if (!isa<RecordType>(C1))
4591 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004592 // heuristic to reduce number of builtin candidates in the set.
4593 // Add volatile/restrict version only if there are conversions to a
4594 // volatile/restrict type.
4595 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4596 continue;
4597 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4598 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004599 }
4600 for (BuiltinCandidateTypeSet::iterator
4601 MemPtr = CandidateTypes.member_pointer_begin(),
4602 MemPtrEnd = CandidateTypes.member_pointer_end();
4603 MemPtr != MemPtrEnd; ++MemPtr) {
4604 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4605 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004606 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004607 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4608 break;
4609 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4610 // build CV12 T&
4611 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004612 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4613 T.isVolatileQualified())
4614 continue;
4615 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4616 T.isRestrictQualified())
4617 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004618 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004619 QualType ResultTy = Context.getLValueReferenceType(T);
4620 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4621 }
4622 }
4623 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004624 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004625
4626 case OO_Conditional:
4627 // Note that we don't consider the first argument, since it has been
4628 // contextually converted to bool long ago. The candidates below are
4629 // therefore added as binary.
4630 //
4631 // C++ [over.built]p24:
4632 // For every type T, where T is a pointer or pointer-to-member type,
4633 // there exist candidate operator functions of the form
4634 //
4635 // T operator?(bool, T, T);
4636 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004637 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4638 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4639 QualType ParamTypes[2] = { *Ptr, *Ptr };
4640 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4641 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004642 for (BuiltinCandidateTypeSet::iterator Ptr =
4643 CandidateTypes.member_pointer_begin(),
4644 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4645 QualType ParamTypes[2] = { *Ptr, *Ptr };
4646 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4647 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004648 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004649 }
4650}
4651
Douglas Gregore254f902009-02-04 00:32:51 +00004652/// \brief Add function candidates found via argument-dependent lookup
4653/// to the set of overloading candidates.
4654///
4655/// This routine performs argument-dependent name lookup based on the
4656/// given function name (which may also be an operator name) and adds
4657/// all of the overload candidates found by ADL to the overload
4658/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004659void
Douglas Gregore254f902009-02-04 00:32:51 +00004660Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004661 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004662 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004663 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004664 OverloadCandidateSet& CandidateSet,
4665 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004666 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004667
John McCall91f61fc2010-01-26 06:04:06 +00004668 // FIXME: This approach for uniquing ADL results (and removing
4669 // redundant candidates from the set) relies on pointer-equality,
4670 // which means we need to key off the canonical decl. However,
4671 // always going back to the canonical decl might not get us the
4672 // right set of default arguments. What default arguments are
4673 // we supposed to consider on ADL candidates, anyway?
4674
Douglas Gregorcabea402009-09-22 15:41:20 +00004675 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004676 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004677
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004678 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004679 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4680 CandEnd = CandidateSet.end();
4681 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004682 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004683 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004684 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004685 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004686 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004687
4688 // For each of the ADL candidates we found, add it to the overload
4689 // set.
John McCall8fe68082010-01-26 07:16:45 +00004690 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004691 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004692 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004693 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004694 continue;
4695
John McCalla0296f72010-03-19 07:35:19 +00004696 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004697 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004698 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004699 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004700 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004701 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004702 }
Douglas Gregore254f902009-02-04 00:32:51 +00004703}
4704
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004705/// isBetterOverloadCandidate - Determines whether the first overload
4706/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004707bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004708Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004709 const OverloadCandidate& Cand2,
4710 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004711 // Define viable functions to be better candidates than non-viable
4712 // functions.
4713 if (!Cand2.Viable)
4714 return Cand1.Viable;
4715 else if (!Cand1.Viable)
4716 return false;
4717
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004718 // C++ [over.match.best]p1:
4719 //
4720 // -- if F is a static member function, ICS1(F) is defined such
4721 // that ICS1(F) is neither better nor worse than ICS1(G) for
4722 // any function G, and, symmetrically, ICS1(G) is neither
4723 // better nor worse than ICS1(F).
4724 unsigned StartArg = 0;
4725 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4726 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004727
Douglas Gregord3cb3562009-07-07 23:38:56 +00004728 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004729 // A viable function F1 is defined to be a better function than another
4730 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004731 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004732 unsigned NumArgs = Cand1.Conversions.size();
4733 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4734 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004735 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004736 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4737 Cand2.Conversions[ArgIdx])) {
4738 case ImplicitConversionSequence::Better:
4739 // Cand1 has a better conversion sequence.
4740 HasBetterConversion = true;
4741 break;
4742
4743 case ImplicitConversionSequence::Worse:
4744 // Cand1 can't be better than Cand2.
4745 return false;
4746
4747 case ImplicitConversionSequence::Indistinguishable:
4748 // Do nothing.
4749 break;
4750 }
4751 }
4752
Mike Stump11289f42009-09-09 15:08:12 +00004753 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004754 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004755 if (HasBetterConversion)
4756 return true;
4757
Mike Stump11289f42009-09-09 15:08:12 +00004758 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004759 // specialization, or, if not that,
4760 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4761 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4762 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004763
4764 // -- F1 and F2 are function template specializations, and the function
4765 // template for F1 is more specialized than the template for F2
4766 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004767 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004768 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4769 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004770 if (FunctionTemplateDecl *BetterTemplate
4771 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4772 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004773 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004774 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4775 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004776 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004777
Douglas Gregora1f013e2008-11-07 22:36:19 +00004778 // -- the context is an initialization by user-defined conversion
4779 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4780 // from the return type of F1 to the destination type (i.e.,
4781 // the type of the entity being initialized) is a better
4782 // conversion sequence than the standard conversion sequence
4783 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004784 if (Cand1.Function && Cand2.Function &&
4785 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004786 isa<CXXConversionDecl>(Cand2.Function)) {
4787 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4788 Cand2.FinalConversion)) {
4789 case ImplicitConversionSequence::Better:
4790 // Cand1 has a better conversion sequence.
4791 return true;
4792
4793 case ImplicitConversionSequence::Worse:
4794 // Cand1 can't be better than Cand2.
4795 return false;
4796
4797 case ImplicitConversionSequence::Indistinguishable:
4798 // Do nothing
4799 break;
4800 }
4801 }
4802
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004803 return false;
4804}
4805
Mike Stump11289f42009-09-09 15:08:12 +00004806/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004807/// within an overload candidate set.
4808///
4809/// \param CandidateSet the set of candidate functions.
4810///
4811/// \param Loc the location of the function name (or operator symbol) for
4812/// which overload resolution occurs.
4813///
Mike Stump11289f42009-09-09 15:08:12 +00004814/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004815/// function, Best points to the candidate function found.
4816///
4817/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004818OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4819 SourceLocation Loc,
4820 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004821 // Find the best viable function.
4822 Best = CandidateSet.end();
4823 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4824 Cand != CandidateSet.end(); ++Cand) {
4825 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004826 if (Best == CandidateSet.end() ||
4827 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004828 Best = Cand;
4829 }
4830 }
4831
4832 // If we didn't find any viable functions, abort.
4833 if (Best == CandidateSet.end())
4834 return OR_No_Viable_Function;
4835
4836 // Make sure that this function is better than every other viable
4837 // function. If not, we have an ambiguity.
4838 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4839 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004840 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004841 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004842 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004843 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004844 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004845 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004846 }
Mike Stump11289f42009-09-09 15:08:12 +00004847
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004848 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004849 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004850 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004851 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004852 return OR_Deleted;
4853
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004854 // C++ [basic.def.odr]p2:
4855 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004856 // when referred to from a potentially-evaluated expression. [Note: this
4857 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004858 // (clause 13), user-defined conversions (12.3.2), allocation function for
4859 // placement new (5.3.4), as well as non-default initialization (8.5).
4860 if (Best->Function)
4861 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004862 return OR_Success;
4863}
4864
John McCall53262c92010-01-12 02:15:36 +00004865namespace {
4866
4867enum OverloadCandidateKind {
4868 oc_function,
4869 oc_method,
4870 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004871 oc_function_template,
4872 oc_method_template,
4873 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004874 oc_implicit_default_constructor,
4875 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004876 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004877};
4878
John McCalle1ac8d12010-01-13 00:25:19 +00004879OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4880 FunctionDecl *Fn,
4881 std::string &Description) {
4882 bool isTemplate = false;
4883
4884 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4885 isTemplate = true;
4886 Description = S.getTemplateArgumentBindingsText(
4887 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4888 }
John McCallfd0b2f82010-01-06 09:43:14 +00004889
4890 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004891 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004892 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004893
John McCall53262c92010-01-12 02:15:36 +00004894 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4895 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004896 }
4897
4898 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4899 // This actually gets spelled 'candidate function' for now, but
4900 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004901 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004902 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004903
4904 assert(Meth->isCopyAssignment()
4905 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004906 return oc_implicit_copy_assignment;
4907 }
4908
John McCalle1ac8d12010-01-13 00:25:19 +00004909 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004910}
4911
4912} // end anonymous namespace
4913
4914// Notes the location of an overload candidate.
4915void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004916 std::string FnDesc;
4917 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4918 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4919 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004920}
4921
John McCall0d1da222010-01-12 00:44:57 +00004922/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4923/// "lead" diagnostic; it will be given two arguments, the source and
4924/// target types of the conversion.
4925void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4926 SourceLocation CaretLoc,
4927 const PartialDiagnostic &PDiag) {
4928 Diag(CaretLoc, PDiag)
4929 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4930 for (AmbiguousConversionSequence::const_iterator
4931 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4932 NoteOverloadCandidate(*I);
4933 }
John McCall12f97bc2010-01-08 04:41:39 +00004934}
4935
John McCall0d1da222010-01-12 00:44:57 +00004936namespace {
4937
John McCall6a61b522010-01-13 09:16:55 +00004938void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4939 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4940 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004941 assert(Cand->Function && "for now, candidate must be a function");
4942 FunctionDecl *Fn = Cand->Function;
4943
4944 // There's a conversion slot for the object argument if this is a
4945 // non-constructor method. Note that 'I' corresponds the
4946 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004947 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004948 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004949 if (I == 0)
4950 isObjectArgument = true;
4951 else
4952 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004953 }
4954
John McCalle1ac8d12010-01-13 00:25:19 +00004955 std::string FnDesc;
4956 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4957
John McCall6a61b522010-01-13 09:16:55 +00004958 Expr *FromExpr = Conv.Bad.FromExpr;
4959 QualType FromTy = Conv.Bad.getFromType();
4960 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004961
John McCallfb7ad0f2010-02-02 02:42:52 +00004962 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004963 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004964 Expr *E = FromExpr->IgnoreParens();
4965 if (isa<UnaryOperator>(E))
4966 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004967 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004968
4969 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4970 << (unsigned) FnKind << FnDesc
4971 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4972 << ToTy << Name << I+1;
4973 return;
4974 }
4975
John McCall6d174642010-01-23 08:10:49 +00004976 // Do some hand-waving analysis to see if the non-viability is due
4977 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004978 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4979 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4980 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4981 CToTy = RT->getPointeeType();
4982 else {
4983 // TODO: detect and diagnose the full richness of const mismatches.
4984 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4985 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4986 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4987 }
4988
4989 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4990 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4991 // It is dumb that we have to do this here.
4992 while (isa<ArrayType>(CFromTy))
4993 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4994 while (isa<ArrayType>(CToTy))
4995 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4996
4997 Qualifiers FromQs = CFromTy.getQualifiers();
4998 Qualifiers ToQs = CToTy.getQualifiers();
4999
5000 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5001 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5002 << (unsigned) FnKind << FnDesc
5003 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5004 << FromTy
5005 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5006 << (unsigned) isObjectArgument << I+1;
5007 return;
5008 }
5009
5010 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5011 assert(CVR && "unexpected qualifiers mismatch");
5012
5013 if (isObjectArgument) {
5014 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5015 << (unsigned) FnKind << FnDesc
5016 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5017 << FromTy << (CVR - 1);
5018 } else {
5019 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5020 << (unsigned) FnKind << FnDesc
5021 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5022 << FromTy << (CVR - 1) << I+1;
5023 }
5024 return;
5025 }
5026
John McCall6d174642010-01-23 08:10:49 +00005027 // Diagnose references or pointers to incomplete types differently,
5028 // since it's far from impossible that the incompleteness triggered
5029 // the failure.
5030 QualType TempFromTy = FromTy.getNonReferenceType();
5031 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5032 TempFromTy = PTy->getPointeeType();
5033 if (TempFromTy->isIncompleteType()) {
5034 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5035 << (unsigned) FnKind << FnDesc
5036 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5037 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5038 return;
5039 }
5040
John McCall47000992010-01-14 03:28:57 +00005041 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005042 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5043 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005044 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005045 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005046}
5047
5048void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5049 unsigned NumFormalArgs) {
5050 // TODO: treat calls to a missing default constructor as a special case
5051
5052 FunctionDecl *Fn = Cand->Function;
5053 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5054
5055 unsigned MinParams = Fn->getMinRequiredArguments();
5056
5057 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005058 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005059 unsigned mode, modeCount;
5060 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005061 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5062 (Cand->FailureKind == ovl_fail_bad_deduction &&
5063 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005064 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5065 mode = 0; // "at least"
5066 else
5067 mode = 2; // "exactly"
5068 modeCount = MinParams;
5069 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005070 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5071 (Cand->FailureKind == ovl_fail_bad_deduction &&
5072 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005073 if (MinParams != FnTy->getNumArgs())
5074 mode = 1; // "at most"
5075 else
5076 mode = 2; // "exactly"
5077 modeCount = FnTy->getNumArgs();
5078 }
5079
5080 std::string Description;
5081 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5082
5083 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005084 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5085 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005086}
5087
John McCall8b9ed552010-02-01 18:53:26 +00005088/// Diagnose a failed template-argument deduction.
5089void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5090 Expr **Args, unsigned NumArgs) {
5091 FunctionDecl *Fn = Cand->Function; // pattern
5092
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005093 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
John McCall8b9ed552010-02-01 18:53:26 +00005094 switch (Cand->DeductionFailure.Result) {
5095 case Sema::TDK_Success:
5096 llvm_unreachable("TDK_success while diagnosing bad deduction");
5097
5098 case Sema::TDK_Incomplete: {
5099 NamedDecl *ParamD;
5100 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5101 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5102 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
5103 assert(ParamD && "no parameter found for incomplete deduction result");
5104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5105 << ParamD->getDeclName();
5106 return;
5107 }
5108
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005109 case Sema::TDK_Inconsistent:
5110 case Sema::TDK_InconsistentQuals: {
5111 NamedDecl *ParamD;
5112 int which = 0;
5113 if ((ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()))
5114 which = 0;
5115 else if ((ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()))
5116 which = 1;
5117 else {
5118 ParamD = Param.get<TemplateTemplateParmDecl*>();
5119 which = 2;
5120 }
5121
5122 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5123 << which << ParamD->getDeclName()
5124 << *Cand->DeductionFailure.getFirstArg()
5125 << *Cand->DeductionFailure.getSecondArg();
5126 return;
5127 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005128
5129 case Sema::TDK_TooManyArguments:
5130 case Sema::TDK_TooFewArguments:
5131 DiagnoseArityMismatch(S, Cand, NumArgs);
5132 return;
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005133
John McCall8b9ed552010-02-01 18:53:26 +00005134 // TODO: diagnose these individually, then kill off
5135 // note_ovl_candidate_bad_deduction, which is uselessly vague.
5136 case Sema::TDK_InstantiationDepth:
John McCall8b9ed552010-02-01 18:53:26 +00005137 case Sema::TDK_SubstitutionFailure:
5138 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005139 case Sema::TDK_InvalidExplicitArguments:
5140 case Sema::TDK_FailedOverloadResolution:
5141 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5142 return;
5143 }
5144}
5145
5146/// Generates a 'note' diagnostic for an overload candidate. We've
5147/// already generated a primary error at the call site.
5148///
5149/// It really does need to be a single diagnostic with its caret
5150/// pointed at the candidate declaration. Yes, this creates some
5151/// major challenges of technical writing. Yes, this makes pointing
5152/// out problems with specific arguments quite awkward. It's still
5153/// better than generating twenty screens of text for every failed
5154/// overload.
5155///
5156/// It would be great to be able to express per-candidate problems
5157/// more richly for those diagnostic clients that cared, but we'd
5158/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005159void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5160 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005161 FunctionDecl *Fn = Cand->Function;
5162
John McCall12f97bc2010-01-08 04:41:39 +00005163 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005164 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005165 std::string FnDesc;
5166 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005167
5168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005169 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005170 return;
John McCall12f97bc2010-01-08 04:41:39 +00005171 }
5172
John McCalle1ac8d12010-01-13 00:25:19 +00005173 // We don't really have anything else to say about viable candidates.
5174 if (Cand->Viable) {
5175 S.NoteOverloadCandidate(Fn);
5176 return;
5177 }
John McCall0d1da222010-01-12 00:44:57 +00005178
John McCall6a61b522010-01-13 09:16:55 +00005179 switch (Cand->FailureKind) {
5180 case ovl_fail_too_many_arguments:
5181 case ovl_fail_too_few_arguments:
5182 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005183
John McCall6a61b522010-01-13 09:16:55 +00005184 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005185 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5186
John McCallfe796dd2010-01-23 05:17:32 +00005187 case ovl_fail_trivial_conversion:
5188 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005189 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005190 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005191
John McCall65eb8792010-02-25 01:37:24 +00005192 case ovl_fail_bad_conversion: {
5193 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5194 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005195 if (Cand->Conversions[I].isBad())
5196 return DiagnoseBadConversion(S, Cand, I);
5197
5198 // FIXME: this currently happens when we're called from SemaInit
5199 // when user-conversion overload fails. Figure out how to handle
5200 // those conditions and diagnose them well.
5201 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005202 }
John McCall65eb8792010-02-25 01:37:24 +00005203 }
John McCalld3224162010-01-08 00:58:21 +00005204}
5205
5206void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5207 // Desugar the type of the surrogate down to a function type,
5208 // retaining as many typedefs as possible while still showing
5209 // the function type (and, therefore, its parameter types).
5210 QualType FnType = Cand->Surrogate->getConversionType();
5211 bool isLValueReference = false;
5212 bool isRValueReference = false;
5213 bool isPointer = false;
5214 if (const LValueReferenceType *FnTypeRef =
5215 FnType->getAs<LValueReferenceType>()) {
5216 FnType = FnTypeRef->getPointeeType();
5217 isLValueReference = true;
5218 } else if (const RValueReferenceType *FnTypeRef =
5219 FnType->getAs<RValueReferenceType>()) {
5220 FnType = FnTypeRef->getPointeeType();
5221 isRValueReference = true;
5222 }
5223 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5224 FnType = FnTypePtr->getPointeeType();
5225 isPointer = true;
5226 }
5227 // Desugar down to a function type.
5228 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5229 // Reconstruct the pointer/reference as appropriate.
5230 if (isPointer) FnType = S.Context.getPointerType(FnType);
5231 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5232 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5233
5234 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5235 << FnType;
5236}
5237
5238void NoteBuiltinOperatorCandidate(Sema &S,
5239 const char *Opc,
5240 SourceLocation OpLoc,
5241 OverloadCandidate *Cand) {
5242 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5243 std::string TypeStr("operator");
5244 TypeStr += Opc;
5245 TypeStr += "(";
5246 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5247 if (Cand->Conversions.size() == 1) {
5248 TypeStr += ")";
5249 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5250 } else {
5251 TypeStr += ", ";
5252 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5253 TypeStr += ")";
5254 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5255 }
5256}
5257
5258void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5259 OverloadCandidate *Cand) {
5260 unsigned NoOperands = Cand->Conversions.size();
5261 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5262 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005263 if (ICS.isBad()) break; // all meaningless after first invalid
5264 if (!ICS.isAmbiguous()) continue;
5265
5266 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005267 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005268 }
5269}
5270
John McCall3712d9e2010-01-15 23:32:50 +00005271SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5272 if (Cand->Function)
5273 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005274 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005275 return Cand->Surrogate->getLocation();
5276 return SourceLocation();
5277}
5278
John McCallad2587a2010-01-12 00:48:53 +00005279struct CompareOverloadCandidatesForDisplay {
5280 Sema &S;
5281 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005282
5283 bool operator()(const OverloadCandidate *L,
5284 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005285 // Fast-path this check.
5286 if (L == R) return false;
5287
John McCall12f97bc2010-01-08 04:41:39 +00005288 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005289 if (L->Viable) {
5290 if (!R->Viable) return true;
5291
5292 // TODO: introduce a tri-valued comparison for overload
5293 // candidates. Would be more worthwhile if we had a sort
5294 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005295 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5296 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005297 } else if (R->Viable)
5298 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005299
John McCall3712d9e2010-01-15 23:32:50 +00005300 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005301
John McCall3712d9e2010-01-15 23:32:50 +00005302 // Criteria by which we can sort non-viable candidates:
5303 if (!L->Viable) {
5304 // 1. Arity mismatches come after other candidates.
5305 if (L->FailureKind == ovl_fail_too_many_arguments ||
5306 L->FailureKind == ovl_fail_too_few_arguments)
5307 return false;
5308 if (R->FailureKind == ovl_fail_too_many_arguments ||
5309 R->FailureKind == ovl_fail_too_few_arguments)
5310 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005311
John McCallfe796dd2010-01-23 05:17:32 +00005312 // 2. Bad conversions come first and are ordered by the number
5313 // of bad conversions and quality of good conversions.
5314 if (L->FailureKind == ovl_fail_bad_conversion) {
5315 if (R->FailureKind != ovl_fail_bad_conversion)
5316 return true;
5317
5318 // If there's any ordering between the defined conversions...
5319 // FIXME: this might not be transitive.
5320 assert(L->Conversions.size() == R->Conversions.size());
5321
5322 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005323 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5324 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005325 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5326 R->Conversions[I])) {
5327 case ImplicitConversionSequence::Better:
5328 leftBetter++;
5329 break;
5330
5331 case ImplicitConversionSequence::Worse:
5332 leftBetter--;
5333 break;
5334
5335 case ImplicitConversionSequence::Indistinguishable:
5336 break;
5337 }
5338 }
5339 if (leftBetter > 0) return true;
5340 if (leftBetter < 0) return false;
5341
5342 } else if (R->FailureKind == ovl_fail_bad_conversion)
5343 return false;
5344
John McCall3712d9e2010-01-15 23:32:50 +00005345 // TODO: others?
5346 }
5347
5348 // Sort everything else by location.
5349 SourceLocation LLoc = GetLocationForCandidate(L);
5350 SourceLocation RLoc = GetLocationForCandidate(R);
5351
5352 // Put candidates without locations (e.g. builtins) at the end.
5353 if (LLoc.isInvalid()) return false;
5354 if (RLoc.isInvalid()) return true;
5355
5356 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005357 }
5358};
5359
John McCallfe796dd2010-01-23 05:17:32 +00005360/// CompleteNonViableCandidate - Normally, overload resolution only
5361/// computes up to the first
5362void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5363 Expr **Args, unsigned NumArgs) {
5364 assert(!Cand->Viable);
5365
5366 // Don't do anything on failures other than bad conversion.
5367 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5368
5369 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005370 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005371 unsigned ConvCount = Cand->Conversions.size();
5372 while (true) {
5373 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5374 ConvIdx++;
5375 if (Cand->Conversions[ConvIdx - 1].isBad())
5376 break;
5377 }
5378
5379 if (ConvIdx == ConvCount)
5380 return;
5381
John McCall65eb8792010-02-25 01:37:24 +00005382 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5383 "remaining conversion is initialized?");
5384
Douglas Gregoradc7a702010-04-16 17:45:54 +00005385 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005386 // operation somehow.
5387 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005388
5389 const FunctionProtoType* Proto;
5390 unsigned ArgIdx = ConvIdx;
5391
5392 if (Cand->IsSurrogate) {
5393 QualType ConvType
5394 = Cand->Surrogate->getConversionType().getNonReferenceType();
5395 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5396 ConvType = ConvPtrType->getPointeeType();
5397 Proto = ConvType->getAs<FunctionProtoType>();
5398 ArgIdx--;
5399 } else if (Cand->Function) {
5400 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5401 if (isa<CXXMethodDecl>(Cand->Function) &&
5402 !isa<CXXConstructorDecl>(Cand->Function))
5403 ArgIdx--;
5404 } else {
5405 // Builtin binary operator with a bad first conversion.
5406 assert(ConvCount <= 3);
5407 for (; ConvIdx != ConvCount; ++ConvIdx)
5408 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005409 = TryCopyInitialization(S, Args[ConvIdx],
5410 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5411 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005412 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005413 return;
5414 }
5415
5416 // Fill in the rest of the conversions.
5417 unsigned NumArgsInProto = Proto->getNumArgs();
5418 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5419 if (ArgIdx < NumArgsInProto)
5420 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005421 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5422 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005423 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005424 else
5425 Cand->Conversions[ConvIdx].setEllipsis();
5426 }
5427}
5428
John McCalld3224162010-01-08 00:58:21 +00005429} // end anonymous namespace
5430
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005431/// PrintOverloadCandidates - When overload resolution fails, prints
5432/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005433/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005434void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005435Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005436 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005437 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005438 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005439 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005440 // Sort the candidates by viability and position. Sorting directly would
5441 // be prohibitive, so we make a set of pointers and sort those.
5442 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5443 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5444 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5445 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005446 Cand != LastCand; ++Cand) {
5447 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005448 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005449 else if (OCD == OCD_AllCandidates) {
5450 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5451 Cands.push_back(Cand);
5452 }
5453 }
5454
John McCallad2587a2010-01-12 00:48:53 +00005455 std::sort(Cands.begin(), Cands.end(),
5456 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005457
John McCall0d1da222010-01-12 00:44:57 +00005458 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005459
John McCall12f97bc2010-01-08 04:41:39 +00005460 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5461 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5462 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005463
John McCalld3224162010-01-08 00:58:21 +00005464 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005465 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005466 else if (Cand->IsSurrogate)
5467 NoteSurrogateCandidate(*this, Cand);
5468
5469 // This a builtin candidate. We do not, in general, want to list
5470 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005471 else if (Cand->Viable) {
5472 // Generally we only see ambiguities including viable builtin
5473 // operators if overload resolution got screwed up by an
5474 // ambiguous user-defined conversion.
5475 //
5476 // FIXME: It's quite possible for different conversions to see
5477 // different ambiguities, though.
5478 if (!ReportedAmbiguousConversions) {
5479 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5480 ReportedAmbiguousConversions = true;
5481 }
John McCalld3224162010-01-08 00:58:21 +00005482
John McCall0d1da222010-01-12 00:44:57 +00005483 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005484 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005485 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005486 }
5487}
5488
John McCalla0296f72010-03-19 07:35:19 +00005489static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005490 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005491 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005492
John McCalla0296f72010-03-19 07:35:19 +00005493 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005494}
5495
Douglas Gregorcd695e52008-11-10 20:40:00 +00005496/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5497/// an overloaded function (C++ [over.over]), where @p From is an
5498/// expression with overloaded function type and @p ToType is the type
5499/// we're trying to resolve to. For example:
5500///
5501/// @code
5502/// int f(double);
5503/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005504///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005505/// int (*pfd)(double) = f; // selects f(double)
5506/// @endcode
5507///
5508/// This routine returns the resulting FunctionDecl if it could be
5509/// resolved, and NULL otherwise. When @p Complain is true, this
5510/// routine will emit diagnostics if there is an error.
5511FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005512Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005513 bool Complain,
5514 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005515 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005516 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005517 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005518 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005519 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005520 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005521 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005522 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005523 FunctionType = MemTypePtr->getPointeeType();
5524 IsMember = true;
5525 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005526
Douglas Gregorcd695e52008-11-10 20:40:00 +00005527 // C++ [over.over]p1:
5528 // [...] [Note: any redundant set of parentheses surrounding the
5529 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005530 // C++ [over.over]p1:
5531 // [...] The overloaded function name can be preceded by the &
5532 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005533 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5534 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5535 if (OvlExpr->hasExplicitTemplateArgs()) {
5536 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5537 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005538 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005539
5540 // We expect a pointer or reference to function, or a function pointer.
5541 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5542 if (!FunctionType->isFunctionType()) {
5543 if (Complain)
5544 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5545 << OvlExpr->getName() << ToType;
5546
5547 return 0;
5548 }
5549
5550 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005551
Douglas Gregorcd695e52008-11-10 20:40:00 +00005552 // Look through all of the overloaded functions, searching for one
5553 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005554 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005555 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5556
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005557 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005558 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5559 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005560 // Look through any using declarations to find the underlying function.
5561 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5562
Douglas Gregorcd695e52008-11-10 20:40:00 +00005563 // C++ [over.over]p3:
5564 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005565 // targets of type "pointer-to-function" or "reference-to-function."
5566 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005567 // type "pointer-to-member-function."
5568 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005569
Mike Stump11289f42009-09-09 15:08:12 +00005570 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005571 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005572 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005573 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005574 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005575 // static when converting to member pointer.
5576 if (Method->isStatic() == IsMember)
5577 continue;
5578 } else if (IsMember)
5579 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005580
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005581 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005582 // If the name is a function template, template argument deduction is
5583 // done (14.8.2.2), and if the argument deduction succeeds, the
5584 // resulting template argument list is used to generate a single
5585 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005586 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005587 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005588 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005589 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005590 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005591 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005592 FunctionType, Specialization, Info)) {
5593 // FIXME: make a note of the failed deduction for diagnostics.
5594 (void)Result;
5595 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005596 // FIXME: If the match isn't exact, shouldn't we just drop this as
5597 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005598 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005599 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005600 Matches.push_back(std::make_pair(I.getPair(),
5601 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005602 }
John McCalld14a8642009-11-21 08:51:07 +00005603
5604 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005605 }
Mike Stump11289f42009-09-09 15:08:12 +00005606
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005607 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005608 // Skip non-static functions when converting to pointer, and static
5609 // when converting to member pointer.
5610 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005611 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005612
5613 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005614 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005615 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005616 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005617 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005618
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005619 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005620 QualType ResultTy;
5621 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5622 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5623 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005624 Matches.push_back(std::make_pair(I.getPair(),
5625 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005626 FoundNonTemplateFunction = true;
5627 }
Mike Stump11289f42009-09-09 15:08:12 +00005628 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005629 }
5630
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005631 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005632 if (Matches.empty()) {
5633 if (Complain) {
5634 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5635 << OvlExpr->getName() << FunctionType;
5636 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5637 E = OvlExpr->decls_end();
5638 I != E; ++I)
5639 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5640 NoteOverloadCandidate(F);
5641 }
5642
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005643 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005644 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005645 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005646 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005647 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005648 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005649 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005650 return Result;
5651 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005652
5653 // C++ [over.over]p4:
5654 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005655 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005656 // [...] and any given function template specialization F1 is
5657 // eliminated if the set contains a second function template
5658 // specialization whose function template is more specialized
5659 // than the function template of F1 according to the partial
5660 // ordering rules of 14.5.5.2.
5661
5662 // The algorithm specified above is quadratic. We instead use a
5663 // two-pass algorithm (similar to the one used to identify the
5664 // best viable function in an overload set) that identifies the
5665 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005666
5667 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5668 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5669 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005670
5671 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005672 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005673 TPOC_Other, From->getLocStart(),
5674 PDiag(),
5675 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005676 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005677 PDiag(diag::note_ovl_candidate)
5678 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005679 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005680 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005681 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005682 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00005683 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00005684 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5685 }
John McCall58cc69d2010-01-27 01:50:18 +00005686 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005687 }
Mike Stump11289f42009-09-09 15:08:12 +00005688
Douglas Gregorfae1d712009-09-26 03:56:17 +00005689 // [...] any function template specializations in the set are
5690 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005691 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005692 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005693 ++I;
5694 else {
John McCalla0296f72010-03-19 07:35:19 +00005695 Matches[I] = Matches[--N];
5696 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005697 }
5698 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005699
Mike Stump11289f42009-09-09 15:08:12 +00005700 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005701 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005702 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005703 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005704 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005705 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00005706 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00005707 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5708 }
John McCalla0296f72010-03-19 07:35:19 +00005709 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005710 }
Mike Stump11289f42009-09-09 15:08:12 +00005711
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005712 // FIXME: We should probably return the same thing that BestViableFunction
5713 // returns (even if we issue the diagnostics here).
5714 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005715 << Matches[0].second->getDeclName();
5716 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5717 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005718 return 0;
5719}
5720
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005721/// \brief Given an expression that refers to an overloaded function, try to
5722/// resolve that overloaded function expression down to a single function.
5723///
5724/// This routine can only resolve template-ids that refer to a single function
5725/// template, where that template-id refers to a single template whose template
5726/// arguments are either provided by the template-id or have defaults,
5727/// as described in C++0x [temp.arg.explicit]p3.
5728FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5729 // C++ [over.over]p1:
5730 // [...] [Note: any redundant set of parentheses surrounding the
5731 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005732 // C++ [over.over]p1:
5733 // [...] The overloaded function name can be preceded by the &
5734 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005735
5736 if (From->getType() != Context.OverloadTy)
5737 return 0;
5738
5739 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005740
5741 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005742 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005743 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005744
5745 TemplateArgumentListInfo ExplicitTemplateArgs;
5746 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005747
5748 // Look through all of the overloaded functions, searching for one
5749 // whose type matches exactly.
5750 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005751 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5752 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005753 // C++0x [temp.arg.explicit]p3:
5754 // [...] In contexts where deduction is done and fails, or in contexts
5755 // where deduction is not done, if a template argument list is
5756 // specified and it, along with any default template arguments,
5757 // identifies a single function template specialization, then the
5758 // template-id is an lvalue for the function template specialization.
5759 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5760
5761 // C++ [over.over]p2:
5762 // If the name is a function template, template argument deduction is
5763 // done (14.8.2.2), and if the argument deduction succeeds, the
5764 // resulting template argument list is used to generate a single
5765 // function template specialization, which is added to the set of
5766 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005767 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005768 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005769 if (TemplateDeductionResult Result
5770 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5771 Specialization, Info)) {
5772 // FIXME: make a note of the failed deduction for diagnostics.
5773 (void)Result;
5774 continue;
5775 }
5776
5777 // Multiple matches; we can't resolve to a single declaration.
5778 if (Matched)
5779 return 0;
5780
5781 Matched = Specialization;
5782 }
5783
5784 return Matched;
5785}
5786
Douglas Gregorcabea402009-09-22 15:41:20 +00005787/// \brief Add a single candidate to the overload set.
5788static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005789 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005790 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005791 Expr **Args, unsigned NumArgs,
5792 OverloadCandidateSet &CandidateSet,
5793 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005794 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005795 if (isa<UsingShadowDecl>(Callee))
5796 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5797
Douglas Gregorcabea402009-09-22 15:41:20 +00005798 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005799 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005800 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005801 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005802 return;
John McCalld14a8642009-11-21 08:51:07 +00005803 }
5804
5805 if (FunctionTemplateDecl *FuncTemplate
5806 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005807 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5808 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005809 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005810 return;
5811 }
5812
5813 assert(false && "unhandled case in overloaded call candidate");
5814
5815 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005816}
5817
5818/// \brief Add the overload candidates named by callee and/or found by argument
5819/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005820void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005821 Expr **Args, unsigned NumArgs,
5822 OverloadCandidateSet &CandidateSet,
5823 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005824
5825#ifndef NDEBUG
5826 // Verify that ArgumentDependentLookup is consistent with the rules
5827 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005828 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005829 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5830 // and let Y be the lookup set produced by argument dependent
5831 // lookup (defined as follows). If X contains
5832 //
5833 // -- a declaration of a class member, or
5834 //
5835 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005836 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005837 //
5838 // -- a declaration that is neither a function or a function
5839 // template
5840 //
5841 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005842
John McCall57500772009-12-16 12:17:52 +00005843 if (ULE->requiresADL()) {
5844 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5845 E = ULE->decls_end(); I != E; ++I) {
5846 assert(!(*I)->getDeclContext()->isRecord());
5847 assert(isa<UsingShadowDecl>(*I) ||
5848 !(*I)->getDeclContext()->isFunctionOrMethod());
5849 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005850 }
5851 }
5852#endif
5853
John McCall57500772009-12-16 12:17:52 +00005854 // It would be nice to avoid this copy.
5855 TemplateArgumentListInfo TABuffer;
5856 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5857 if (ULE->hasExplicitTemplateArgs()) {
5858 ULE->copyTemplateArgumentsInto(TABuffer);
5859 ExplicitTemplateArgs = &TABuffer;
5860 }
5861
5862 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5863 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005864 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005865 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005866 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005867
John McCall57500772009-12-16 12:17:52 +00005868 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005869 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5870 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005871 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005872 CandidateSet,
5873 PartialOverloading);
5874}
John McCalld681c392009-12-16 08:11:27 +00005875
John McCall57500772009-12-16 12:17:52 +00005876static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5877 Expr **Args, unsigned NumArgs) {
5878 Fn->Destroy(SemaRef.Context);
5879 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5880 Args[Arg]->Destroy(SemaRef.Context);
5881 return SemaRef.ExprError();
5882}
5883
John McCalld681c392009-12-16 08:11:27 +00005884/// Attempts to recover from a call where no functions were found.
5885///
5886/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005887static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005888BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005889 UnresolvedLookupExpr *ULE,
5890 SourceLocation LParenLoc,
5891 Expr **Args, unsigned NumArgs,
5892 SourceLocation *CommaLocs,
5893 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005894
5895 CXXScopeSpec SS;
5896 if (ULE->getQualifier()) {
5897 SS.setScopeRep(ULE->getQualifier());
5898 SS.setRange(ULE->getQualifierRange());
5899 }
5900
John McCall57500772009-12-16 12:17:52 +00005901 TemplateArgumentListInfo TABuffer;
5902 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5903 if (ULE->hasExplicitTemplateArgs()) {
5904 ULE->copyTemplateArgumentsInto(TABuffer);
5905 ExplicitTemplateArgs = &TABuffer;
5906 }
5907
John McCalld681c392009-12-16 08:11:27 +00005908 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5909 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005910 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005911 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005912
John McCall57500772009-12-16 12:17:52 +00005913 assert(!R.empty() && "lookup results empty despite recovery");
5914
5915 // Build an implicit member call if appropriate. Just drop the
5916 // casts and such from the call, we don't really care.
5917 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5918 if ((*R.begin())->isCXXClassMember())
5919 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5920 else if (ExplicitTemplateArgs)
5921 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5922 else
5923 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5924
5925 if (NewFn.isInvalid())
5926 return Destroy(SemaRef, Fn, Args, NumArgs);
5927
5928 Fn->Destroy(SemaRef.Context);
5929
5930 // This shouldn't cause an infinite loop because we're giving it
5931 // an expression with non-empty lookup results, which should never
5932 // end up here.
5933 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5934 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5935 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005936}
Douglas Gregorcabea402009-09-22 15:41:20 +00005937
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005938/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005939/// (which eventually refers to the declaration Func) and the call
5940/// arguments Args/NumArgs, attempt to resolve the function call down
5941/// to a specific function. If overload resolution succeeds, returns
5942/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005943/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005944/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005945Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005946Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005947 SourceLocation LParenLoc,
5948 Expr **Args, unsigned NumArgs,
5949 SourceLocation *CommaLocs,
5950 SourceLocation RParenLoc) {
5951#ifndef NDEBUG
5952 if (ULE->requiresADL()) {
5953 // To do ADL, we must have found an unqualified name.
5954 assert(!ULE->getQualifier() && "qualified name with ADL");
5955
5956 // We don't perform ADL for implicit declarations of builtins.
5957 // Verify that this was correctly set up.
5958 FunctionDecl *F;
5959 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5960 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5961 F->getBuiltinID() && F->isImplicit())
5962 assert(0 && "performing ADL for builtin");
5963
5964 // We don't perform ADL in C.
5965 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5966 }
5967#endif
5968
John McCallbc077cf2010-02-08 23:07:23 +00005969 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005970
John McCall57500772009-12-16 12:17:52 +00005971 // Add the functions denoted by the callee to the set of candidate
5972 // functions, including those from argument-dependent lookup.
5973 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005974
5975 // If we found nothing, try to recover.
5976 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5977 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005978 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005979 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00005980 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005981
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005982 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005983 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005984 case OR_Success: {
5985 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00005986 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00005987 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00005988 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00005989 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5990 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005991
5992 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005993 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005994 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005995 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005996 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005997 break;
5998
5999 case OR_Ambiguous:
6000 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006001 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006002 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006003 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006004
6005 case OR_Deleted:
6006 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6007 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006008 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006009 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006010 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006011 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006012 }
6013
6014 // Overload resolution failed. Destroy all of the subexpressions and
6015 // return NULL.
6016 Fn->Destroy(Context);
6017 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6018 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00006019 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006020}
6021
John McCall4c4c1df2010-01-26 03:27:55 +00006022static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006023 return Functions.size() > 1 ||
6024 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6025}
6026
Douglas Gregor084d8552009-03-13 23:49:33 +00006027/// \brief Create a unary operation that may resolve to an overloaded
6028/// operator.
6029///
6030/// \param OpLoc The location of the operator itself (e.g., '*').
6031///
6032/// \param OpcIn The UnaryOperator::Opcode that describes this
6033/// operator.
6034///
6035/// \param Functions The set of non-member functions that will be
6036/// considered by overload resolution. The caller needs to build this
6037/// set based on the context using, e.g.,
6038/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6039/// set should not contain any member functions; those will be added
6040/// by CreateOverloadedUnaryOp().
6041///
6042/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006043Sema::OwningExprResult
6044Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6045 const UnresolvedSetImpl &Fns,
6046 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006047 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6048 Expr *Input = (Expr *)input.get();
6049
6050 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6051 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6052 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6053
6054 Expr *Args[2] = { Input, 0 };
6055 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006056
Douglas Gregor084d8552009-03-13 23:49:33 +00006057 // For post-increment and post-decrement, add the implicit '0' as
6058 // the second argument, so that we know this is a post-increment or
6059 // post-decrement.
6060 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6061 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006062 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006063 SourceLocation());
6064 NumArgs = 2;
6065 }
6066
6067 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00006068 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006069 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006070 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006071 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006072 /*ADL*/ true, IsOverloaded(Fns));
6073 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00006074
Douglas Gregor084d8552009-03-13 23:49:33 +00006075 input.release();
6076 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6077 &Args[0], NumArgs,
6078 Context.DependentTy,
6079 OpLoc));
6080 }
6081
6082 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006083 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006084
6085 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006086 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006087
6088 // Add operator candidates that are member functions.
6089 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6090
John McCall4c4c1df2010-01-26 03:27:55 +00006091 // Add candidates from ADL.
6092 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006093 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006094 /*ExplicitTemplateArgs*/ 0,
6095 CandidateSet);
6096
Douglas Gregor084d8552009-03-13 23:49:33 +00006097 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006098 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006099
6100 // Perform overload resolution.
6101 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006102 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006103 case OR_Success: {
6104 // We found a built-in operator or an overloaded operator.
6105 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006106
Douglas Gregor084d8552009-03-13 23:49:33 +00006107 if (FnDecl) {
6108 // We matched an overloaded operator. Build a call to that
6109 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006110
Douglas Gregor084d8552009-03-13 23:49:33 +00006111 // Convert the arguments.
6112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006113 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006114
John McCall16df1e52010-03-30 21:47:33 +00006115 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6116 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006117 return ExprError();
6118 } else {
6119 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006120 OwningExprResult InputInit
6121 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006122 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006123 SourceLocation(),
6124 move(input));
6125 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006126 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006127
Douglas Gregore6600372009-12-23 17:40:29 +00006128 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006129 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006130 }
6131
John McCall4fa0d5f2010-05-06 18:15:07 +00006132 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6133
Douglas Gregor084d8552009-03-13 23:49:33 +00006134 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006135 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006136
Douglas Gregor084d8552009-03-13 23:49:33 +00006137 // Build the actual expression node.
6138 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6139 SourceLocation());
6140 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006141
Douglas Gregor084d8552009-03-13 23:49:33 +00006142 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006143 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006144 ExprOwningPtr<CallExpr> TheCall(this,
6145 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006146 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006147
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006148 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6149 FnDecl))
6150 return ExprError();
6151
6152 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006153 } else {
6154 // We matched a built-in operator. Convert the arguments, then
6155 // break out so that we will build the appropriate built-in
6156 // operator node.
6157 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006158 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006159 return ExprError();
6160
6161 break;
6162 }
6163 }
6164
6165 case OR_No_Viable_Function:
6166 // No viable function; fall through to handling this as a
6167 // built-in operator, which will produce an error message for us.
6168 break;
6169
6170 case OR_Ambiguous:
6171 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6172 << UnaryOperator::getOpcodeStr(Opc)
6173 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006174 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006175 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006176 return ExprError();
6177
6178 case OR_Deleted:
6179 Diag(OpLoc, diag::err_ovl_deleted_oper)
6180 << Best->Function->isDeleted()
6181 << UnaryOperator::getOpcodeStr(Opc)
6182 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006183 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006184 return ExprError();
6185 }
6186
6187 // Either we found no viable overloaded operator or we matched a
6188 // built-in operator. In either case, fall through to trying to
6189 // build a built-in operation.
6190 input.release();
6191 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6192}
6193
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006194/// \brief Create a binary operation that may resolve to an overloaded
6195/// operator.
6196///
6197/// \param OpLoc The location of the operator itself (e.g., '+').
6198///
6199/// \param OpcIn The BinaryOperator::Opcode that describes this
6200/// operator.
6201///
6202/// \param Functions The set of non-member functions that will be
6203/// considered by overload resolution. The caller needs to build this
6204/// set based on the context using, e.g.,
6205/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6206/// set should not contain any member functions; those will be added
6207/// by CreateOverloadedBinOp().
6208///
6209/// \param LHS Left-hand argument.
6210/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006211Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006212Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006213 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006214 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006215 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006216 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006217 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006218
6219 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6220 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6221 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6222
6223 // If either side is type-dependent, create an appropriate dependent
6224 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006225 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006226 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006227 // If there are no functions to store, just build a dependent
6228 // BinaryOperator or CompoundAssignment.
6229 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6230 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6231 Context.DependentTy, OpLoc));
6232
6233 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6234 Context.DependentTy,
6235 Context.DependentTy,
6236 Context.DependentTy,
6237 OpLoc));
6238 }
John McCall4c4c1df2010-01-26 03:27:55 +00006239
6240 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006241 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006242 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006243 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006244 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006245 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006246
John McCall4c4c1df2010-01-26 03:27:55 +00006247 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006248 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006249 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006250 Context.DependentTy,
6251 OpLoc));
6252 }
6253
6254 // If this is the .* operator, which is not overloadable, just
6255 // create a built-in binary operator.
6256 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006257 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006258
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006259 // If this is the assignment operator, we only perform overload resolution
6260 // if the left-hand side is a class or enumeration type. This is actually
6261 // a hack. The standard requires that we do overload resolution between the
6262 // various built-in candidates, but as DR507 points out, this can lead to
6263 // problems. So we do it this way, which pretty much follows what GCC does.
6264 // Note that we go the traditional code path for compound assignment forms.
6265 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006266 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006267
Douglas Gregor084d8552009-03-13 23:49:33 +00006268 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006269 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006270
6271 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006272 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006273
6274 // Add operator candidates that are member functions.
6275 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6276
John McCall4c4c1df2010-01-26 03:27:55 +00006277 // Add candidates from ADL.
6278 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6279 Args, 2,
6280 /*ExplicitTemplateArgs*/ 0,
6281 CandidateSet);
6282
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006283 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006284 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006285
6286 // Perform overload resolution.
6287 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006288 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006289 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006290 // We found a built-in operator or an overloaded operator.
6291 FunctionDecl *FnDecl = Best->Function;
6292
6293 if (FnDecl) {
6294 // We matched an overloaded operator. Build a call to that
6295 // operator.
6296
6297 // Convert the arguments.
6298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006299 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006300 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006301
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006302 OwningExprResult Arg1
6303 = PerformCopyInitialization(
6304 InitializedEntity::InitializeParameter(
6305 FnDecl->getParamDecl(0)),
6306 SourceLocation(),
6307 Owned(Args[1]));
6308 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006309 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006310
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006311 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006312 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006313 return ExprError();
6314
6315 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006316 } else {
6317 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006318 OwningExprResult Arg0
6319 = PerformCopyInitialization(
6320 InitializedEntity::InitializeParameter(
6321 FnDecl->getParamDecl(0)),
6322 SourceLocation(),
6323 Owned(Args[0]));
6324 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006325 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006326
6327 OwningExprResult Arg1
6328 = PerformCopyInitialization(
6329 InitializedEntity::InitializeParameter(
6330 FnDecl->getParamDecl(1)),
6331 SourceLocation(),
6332 Owned(Args[1]));
6333 if (Arg1.isInvalid())
6334 return ExprError();
6335 Args[0] = LHS = Arg0.takeAs<Expr>();
6336 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006337 }
6338
John McCall4fa0d5f2010-05-06 18:15:07 +00006339 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6340
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006341 // Determine the result type
6342 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006343 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006344 ResultTy = ResultTy.getNonReferenceType();
6345
6346 // Build the actual expression node.
6347 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006348 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006349 UsualUnaryConversions(FnExpr);
6350
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006351 ExprOwningPtr<CXXOperatorCallExpr>
6352 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6353 Args, 2, ResultTy,
6354 OpLoc));
6355
6356 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6357 FnDecl))
6358 return ExprError();
6359
6360 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006361 } else {
6362 // We matched a built-in operator. Convert the arguments, then
6363 // break out so that we will build the appropriate built-in
6364 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006365 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006366 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006367 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006368 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006369 return ExprError();
6370
6371 break;
6372 }
6373 }
6374
Douglas Gregor66950a32009-09-30 21:46:01 +00006375 case OR_No_Viable_Function: {
6376 // C++ [over.match.oper]p9:
6377 // If the operator is the operator , [...] and there are no
6378 // viable functions, then the operator is assumed to be the
6379 // built-in operator and interpreted according to clause 5.
6380 if (Opc == BinaryOperator::Comma)
6381 break;
6382
Sebastian Redl027de2a2009-05-21 11:50:50 +00006383 // For class as left operand for assignment or compound assigment operator
6384 // do not fall through to handling in built-in, but report that no overloaded
6385 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006386 OwningExprResult Result = ExprError();
6387 if (Args[0]->getType()->isRecordType() &&
6388 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006389 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6390 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006391 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006392 } else {
6393 // No viable function; try to create a built-in operation, which will
6394 // produce an error. Then, show the non-viable candidates.
6395 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006396 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006397 assert(Result.isInvalid() &&
6398 "C++ binary operator overloading is missing candidates!");
6399 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006400 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006401 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006402 return move(Result);
6403 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006404
6405 case OR_Ambiguous:
6406 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6407 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006408 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006409 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006410 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006411 return ExprError();
6412
6413 case OR_Deleted:
6414 Diag(OpLoc, diag::err_ovl_deleted_oper)
6415 << Best->Function->isDeleted()
6416 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006417 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006418 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006419 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006420 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006421
Douglas Gregor66950a32009-09-30 21:46:01 +00006422 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006423 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006424}
6425
Sebastian Redladba46e2009-10-29 20:17:01 +00006426Action::OwningExprResult
6427Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6428 SourceLocation RLoc,
6429 ExprArg Base, ExprArg Idx) {
6430 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6431 static_cast<Expr*>(Idx.get()) };
6432 DeclarationName OpName =
6433 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6434
6435 // If either side is type-dependent, create an appropriate dependent
6436 // expression.
6437 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6438
John McCall58cc69d2010-01-27 01:50:18 +00006439 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006440 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006441 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006442 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006443 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006444 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006445
6446 Base.release();
6447 Idx.release();
6448 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6449 Args, 2,
6450 Context.DependentTy,
6451 RLoc));
6452 }
6453
6454 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006455 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006456
6457 // Subscript can only be overloaded as a member function.
6458
6459 // Add operator candidates that are member functions.
6460 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6461
6462 // Add builtin operator candidates.
6463 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6464
6465 // Perform overload resolution.
6466 OverloadCandidateSet::iterator Best;
6467 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6468 case OR_Success: {
6469 // We found a built-in operator or an overloaded operator.
6470 FunctionDecl *FnDecl = Best->Function;
6471
6472 if (FnDecl) {
6473 // We matched an overloaded operator. Build a call to that
6474 // operator.
6475
John McCalla0296f72010-03-19 07:35:19 +00006476 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006477 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006478
Sebastian Redladba46e2009-10-29 20:17:01 +00006479 // Convert the arguments.
6480 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006481 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006482 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006483 return ExprError();
6484
Anders Carlssona68e51e2010-01-29 18:37:50 +00006485 // Convert the arguments.
6486 OwningExprResult InputInit
6487 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6488 FnDecl->getParamDecl(0)),
6489 SourceLocation(),
6490 Owned(Args[1]));
6491 if (InputInit.isInvalid())
6492 return ExprError();
6493
6494 Args[1] = InputInit.takeAs<Expr>();
6495
Sebastian Redladba46e2009-10-29 20:17:01 +00006496 // Determine the result type
6497 QualType ResultTy
6498 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6499 ResultTy = ResultTy.getNonReferenceType();
6500
6501 // Build the actual expression node.
6502 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6503 LLoc);
6504 UsualUnaryConversions(FnExpr);
6505
6506 Base.release();
6507 Idx.release();
6508 ExprOwningPtr<CXXOperatorCallExpr>
6509 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6510 FnExpr, Args, 2,
6511 ResultTy, RLoc));
6512
6513 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6514 FnDecl))
6515 return ExprError();
6516
6517 return MaybeBindToTemporary(TheCall.release());
6518 } else {
6519 // We matched a built-in operator. Convert the arguments, then
6520 // break out so that we will build the appropriate built-in
6521 // operator node.
6522 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006523 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006524 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006525 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006526 return ExprError();
6527
6528 break;
6529 }
6530 }
6531
6532 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006533 if (CandidateSet.empty())
6534 Diag(LLoc, diag::err_ovl_no_oper)
6535 << Args[0]->getType() << /*subscript*/ 0
6536 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6537 else
6538 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6539 << Args[0]->getType()
6540 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006541 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006542 "[]", LLoc);
6543 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006544 }
6545
6546 case OR_Ambiguous:
6547 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6548 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006549 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006550 "[]", LLoc);
6551 return ExprError();
6552
6553 case OR_Deleted:
6554 Diag(LLoc, diag::err_ovl_deleted_oper)
6555 << Best->Function->isDeleted() << "[]"
6556 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006557 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006558 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006559 return ExprError();
6560 }
6561
6562 // We matched a built-in operator; build it.
6563 Base.release();
6564 Idx.release();
6565 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6566 Owned(Args[1]), RLoc);
6567}
6568
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006569/// BuildCallToMemberFunction - Build a call to a member
6570/// function. MemExpr is the expression that refers to the member
6571/// function (and includes the object parameter), Args/NumArgs are the
6572/// arguments to the function call (not including the object
6573/// parameter). The caller needs to validate that the member
6574/// expression refers to a member function or an overloaded member
6575/// function.
John McCall2d74de92009-12-01 22:10:20 +00006576Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006577Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6578 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006579 unsigned NumArgs, SourceLocation *CommaLocs,
6580 SourceLocation RParenLoc) {
6581 // Dig out the member expression. This holds both the object
6582 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006583 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6584
John McCall10eae182009-11-30 22:42:35 +00006585 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006586 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006587 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006588 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006589 if (isa<MemberExpr>(NakedMemExpr)) {
6590 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006591 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006592 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006593 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006594 } else {
6595 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006596 Qualifier = UnresExpr->getQualifier();
6597
John McCall6e9f8f62009-12-03 04:06:58 +00006598 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006599
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006600 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006601 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006602
John McCall2d74de92009-12-01 22:10:20 +00006603 // FIXME: avoid copy.
6604 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6605 if (UnresExpr->hasExplicitTemplateArgs()) {
6606 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6607 TemplateArgs = &TemplateArgsBuffer;
6608 }
6609
John McCall10eae182009-11-30 22:42:35 +00006610 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6611 E = UnresExpr->decls_end(); I != E; ++I) {
6612
John McCall6e9f8f62009-12-03 04:06:58 +00006613 NamedDecl *Func = *I;
6614 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6615 if (isa<UsingShadowDecl>(Func))
6616 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6617
John McCall10eae182009-11-30 22:42:35 +00006618 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006619 // If explicit template arguments were provided, we can't call a
6620 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006621 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006622 continue;
6623
John McCalla0296f72010-03-19 07:35:19 +00006624 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006625 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006626 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006627 } else {
John McCall10eae182009-11-30 22:42:35 +00006628 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006629 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006630 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006631 CandidateSet,
6632 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006633 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006634 }
Mike Stump11289f42009-09-09 15:08:12 +00006635
John McCall10eae182009-11-30 22:42:35 +00006636 DeclarationName DeclName = UnresExpr->getMemberName();
6637
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006638 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006639 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006640 case OR_Success:
6641 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006642 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006643 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006644 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006645 break;
6646
6647 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006648 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006649 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006650 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006651 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006652 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006653 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006654
6655 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006656 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006657 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006658 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006659 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006660 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006661
6662 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006663 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006664 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006665 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006666 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006667 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006668 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006669 }
6670
John McCall16df1e52010-03-30 21:47:33 +00006671 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006672
John McCall2d74de92009-12-01 22:10:20 +00006673 // If overload resolution picked a static member, build a
6674 // non-member call based on that function.
6675 if (Method->isStatic()) {
6676 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6677 Args, NumArgs, RParenLoc);
6678 }
6679
John McCall10eae182009-11-30 22:42:35 +00006680 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006681 }
6682
6683 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006684 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006685 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006686 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006687 Method->getResultType().getNonReferenceType(),
6688 RParenLoc));
6689
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006690 // Check for a valid return type.
6691 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6692 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006693 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006694
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006695 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006696 // We only need to do this if there was actually an overload; otherwise
6697 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006698 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006699 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006700 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6701 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006702 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006703 MemExpr->setBase(ObjectArg);
6704
6705 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00006706 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00006707 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006708 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006709 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006710
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006711 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006712 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006713
John McCall2d74de92009-12-01 22:10:20 +00006714 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006715}
6716
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006717/// BuildCallToObjectOfClassType - Build a call to an object of class
6718/// type (C++ [over.call.object]), which can end up invoking an
6719/// overloaded function call operator (@c operator()) or performing a
6720/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006721Sema::ExprResult
6722Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006723 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006724 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006725 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006726 SourceLocation RParenLoc) {
6727 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006728 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006729
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006730 // C++ [over.call.object]p1:
6731 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006732 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006733 // candidate functions includes at least the function call
6734 // operators of T. The function call operators of T are obtained by
6735 // ordinary lookup of the name operator() in the context of
6736 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006737 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006738 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006739
6740 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006741 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006742 << Object->getSourceRange()))
6743 return true;
6744
John McCall27b18f82009-11-17 02:14:36 +00006745 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6746 LookupQualifiedName(R, Record->getDecl());
6747 R.suppressDiagnostics();
6748
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006749 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006750 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006751 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006752 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006753 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006754 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006755
Douglas Gregorab7897a2008-11-19 22:57:39 +00006756 // C++ [over.call.object]p2:
6757 // In addition, for each conversion function declared in T of the
6758 // form
6759 //
6760 // operator conversion-type-id () cv-qualifier;
6761 //
6762 // where cv-qualifier is the same cv-qualification as, or a
6763 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006764 // denotes the type "pointer to function of (P1,...,Pn) returning
6765 // R", or the type "reference to pointer to function of
6766 // (P1,...,Pn) returning R", or the type "reference to function
6767 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006768 // is also considered as a candidate function. Similarly,
6769 // surrogate call functions are added to the set of candidate
6770 // functions for each conversion function declared in an
6771 // accessible base class provided the function is not hidden
6772 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006773 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006774 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006775 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006776 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006777 NamedDecl *D = *I;
6778 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6779 if (isa<UsingShadowDecl>(D))
6780 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6781
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006782 // Skip over templated conversion functions; they aren't
6783 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006784 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006785 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006786
John McCall6e9f8f62009-12-03 04:06:58 +00006787 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006788
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006789 // Strip the reference type (if any) and then the pointer type (if
6790 // any) to get down to what might be a function type.
6791 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6792 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6793 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006794
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006795 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006796 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006797 Object->getType(), Args, NumArgs,
6798 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006799 }
Mike Stump11289f42009-09-09 15:08:12 +00006800
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006801 // Perform overload resolution.
6802 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006803 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006804 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006805 // Overload resolution succeeded; we'll build the appropriate call
6806 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006807 break;
6808
6809 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006810 if (CandidateSet.empty())
6811 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6812 << Object->getType() << /*call*/ 1
6813 << Object->getSourceRange();
6814 else
6815 Diag(Object->getSourceRange().getBegin(),
6816 diag::err_ovl_no_viable_object_call)
6817 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006818 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006819 break;
6820
6821 case OR_Ambiguous:
6822 Diag(Object->getSourceRange().getBegin(),
6823 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006824 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006825 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006826 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006827
6828 case OR_Deleted:
6829 Diag(Object->getSourceRange().getBegin(),
6830 diag::err_ovl_deleted_object_call)
6831 << Best->Function->isDeleted()
6832 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006833 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006834 break;
Mike Stump11289f42009-09-09 15:08:12 +00006835 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006836
Douglas Gregorab7897a2008-11-19 22:57:39 +00006837 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006838 // We had an error; delete all of the subexpressions and return
6839 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006840 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006841 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006842 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006843 return true;
6844 }
6845
Douglas Gregorab7897a2008-11-19 22:57:39 +00006846 if (Best->Function == 0) {
6847 // Since there is no function declaration, this is one of the
6848 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006849 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006850 = cast<CXXConversionDecl>(
6851 Best->Conversions[0].UserDefined.ConversionFunction);
6852
John McCalla0296f72010-03-19 07:35:19 +00006853 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006854 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006855
Douglas Gregorab7897a2008-11-19 22:57:39 +00006856 // We selected one of the surrogate functions that converts the
6857 // object parameter to a function pointer. Perform the conversion
6858 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006859
6860 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006861 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006862 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6863 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006864
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006865 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006866 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006867 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006868 }
6869
John McCalla0296f72010-03-19 07:35:19 +00006870 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006871 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006872
Douglas Gregorab7897a2008-11-19 22:57:39 +00006873 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6874 // that calls this method, using Object for the implicit object
6875 // parameter and passing along the remaining arguments.
6876 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006877 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006878
6879 unsigned NumArgsInProto = Proto->getNumArgs();
6880 unsigned NumArgsToCheck = NumArgs;
6881
6882 // Build the full argument list for the method call (the
6883 // implicit object parameter is placed at the beginning of the
6884 // list).
6885 Expr **MethodArgs;
6886 if (NumArgs < NumArgsInProto) {
6887 NumArgsToCheck = NumArgsInProto;
6888 MethodArgs = new Expr*[NumArgsInProto + 1];
6889 } else {
6890 MethodArgs = new Expr*[NumArgs + 1];
6891 }
6892 MethodArgs[0] = Object;
6893 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6894 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006895
6896 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006897 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006898 UsualUnaryConversions(NewFn);
6899
6900 // Once we've built TheCall, all of the expressions are properly
6901 // owned.
6902 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006903 ExprOwningPtr<CXXOperatorCallExpr>
6904 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006905 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006906 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006907 delete [] MethodArgs;
6908
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006909 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6910 Method))
6911 return true;
6912
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006913 // We may have default arguments. If so, we need to allocate more
6914 // slots in the call for them.
6915 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006916 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006917 else if (NumArgs > NumArgsInProto)
6918 NumArgsToCheck = NumArgsInProto;
6919
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006920 bool IsError = false;
6921
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006922 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006923 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006924 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006925 TheCall->setArg(0, Object);
6926
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006927
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006928 // Check the argument types.
6929 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006930 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006931 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006932 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006933
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006934 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006935
6936 OwningExprResult InputInit
6937 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6938 Method->getParamDecl(i)),
6939 SourceLocation(), Owned(Arg));
6940
6941 IsError |= InputInit.isInvalid();
6942 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006943 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006944 OwningExprResult DefArg
6945 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6946 if (DefArg.isInvalid()) {
6947 IsError = true;
6948 break;
6949 }
6950
6951 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006952 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006953
6954 TheCall->setArg(i + 1, Arg);
6955 }
6956
6957 // If this is a variadic call, handle args passed through "...".
6958 if (Proto->isVariadic()) {
6959 // Promote the arguments (C99 6.5.2.2p7).
6960 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6961 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006962 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006963 TheCall->setArg(i + 1, Arg);
6964 }
6965 }
6966
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006967 if (IsError) return true;
6968
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006969 if (CheckFunctionCall(Method, TheCall.get()))
6970 return true;
6971
Douglas Gregore5e775b2010-04-13 15:50:39 +00006972 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006973}
6974
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006975/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006976/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006977/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006978Sema::OwningExprResult
6979Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6980 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006981 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006982
John McCallbc077cf2010-02-08 23:07:23 +00006983 SourceLocation Loc = Base->getExprLoc();
6984
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006985 // C++ [over.ref]p1:
6986 //
6987 // [...] An expression x->m is interpreted as (x.operator->())->m
6988 // for a class object x of type T if T::operator->() exists and if
6989 // the operator is selected as the best match function by the
6990 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006991 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006992 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006993 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006994
John McCallbc077cf2010-02-08 23:07:23 +00006995 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006996 PDiag(diag::err_typecheck_incomplete_tag)
6997 << Base->getSourceRange()))
6998 return ExprError();
6999
John McCall27b18f82009-11-17 02:14:36 +00007000 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7001 LookupQualifiedName(R, BaseRecord->getDecl());
7002 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007003
7004 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007005 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007006 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007007 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007008 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007009
7010 // Perform overload resolution.
7011 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007012 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007013 case OR_Success:
7014 // Overload resolution succeeded; we'll build the call below.
7015 break;
7016
7017 case OR_No_Viable_Function:
7018 if (CandidateSet.empty())
7019 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007020 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007021 else
7022 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007023 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007024 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007025 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007026
7027 case OR_Ambiguous:
7028 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007029 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007030 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007031 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007032
7033 case OR_Deleted:
7034 Diag(OpLoc, diag::err_ovl_deleted_oper)
7035 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007036 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007037 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007038 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007039 }
7040
John McCalla0296f72010-03-19 07:35:19 +00007041 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007042 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007043
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007044 // Convert the object parameter.
7045 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007046 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7047 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007048 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007049
7050 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007051 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007052
7053 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007054 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7055 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007056 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007057
7058 QualType ResultTy = Method->getResultType().getNonReferenceType();
7059 ExprOwningPtr<CXXOperatorCallExpr>
7060 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7061 &Base, 1, ResultTy, OpLoc));
7062
7063 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7064 Method))
7065 return ExprError();
7066 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007067}
7068
Douglas Gregorcd695e52008-11-10 20:40:00 +00007069/// FixOverloadedFunctionReference - E is an expression that refers to
7070/// a C++ overloaded function (possibly with some parentheses and
7071/// perhaps a '&' around it). We have resolved the overloaded function
7072/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007073/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007074Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007075 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007076 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007077 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7078 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007079 if (SubExpr == PE->getSubExpr())
7080 return PE->Retain();
7081
7082 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7083 }
7084
7085 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007086 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7087 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007088 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007089 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007090 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007091 if (SubExpr == ICE->getSubExpr())
7092 return ICE->Retain();
7093
7094 return new (Context) ImplicitCastExpr(ICE->getType(),
7095 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007096 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007097 ICE->isLvalueCast());
7098 }
7099
7100 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007101 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007102 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007103 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7104 if (Method->isStatic()) {
7105 // Do nothing: static member functions aren't any different
7106 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007107 } else {
John McCalle66edc12009-11-24 19:00:30 +00007108 // Fix the sub expression, which really has to be an
7109 // UnresolvedLookupExpr holding an overloaded member function
7110 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007111 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7112 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007113 if (SubExpr == UnOp->getSubExpr())
7114 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007115
John McCalld14a8642009-11-21 08:51:07 +00007116 assert(isa<DeclRefExpr>(SubExpr)
7117 && "fixed to something other than a decl ref");
7118 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7119 && "fixed to a member ref with no nested name qualifier");
7120
7121 // We have taken the address of a pointer to member
7122 // function. Perform the computation here so that we get the
7123 // appropriate pointer to member type.
7124 QualType ClassType
7125 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7126 QualType MemPtrType
7127 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7128
7129 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7130 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007131 }
7132 }
John McCall16df1e52010-03-30 21:47:33 +00007133 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7134 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007135 if (SubExpr == UnOp->getSubExpr())
7136 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007137
Douglas Gregor51c538b2009-11-20 19:42:02 +00007138 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7139 Context.getPointerType(SubExpr->getType()),
7140 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007141 }
John McCalld14a8642009-11-21 08:51:07 +00007142
7143 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007144 // FIXME: avoid copy.
7145 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007146 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007147 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7148 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007149 }
7150
John McCalld14a8642009-11-21 08:51:07 +00007151 return DeclRefExpr::Create(Context,
7152 ULE->getQualifier(),
7153 ULE->getQualifierRange(),
7154 Fn,
7155 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007156 Fn->getType(),
7157 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007158 }
7159
John McCall10eae182009-11-30 22:42:35 +00007160 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007161 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007162 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7163 if (MemExpr->hasExplicitTemplateArgs()) {
7164 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7165 TemplateArgs = &TemplateArgsBuffer;
7166 }
John McCall6b51f282009-11-23 01:53:49 +00007167
John McCall2d74de92009-12-01 22:10:20 +00007168 Expr *Base;
7169
7170 // If we're filling in
7171 if (MemExpr->isImplicitAccess()) {
7172 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7173 return DeclRefExpr::Create(Context,
7174 MemExpr->getQualifier(),
7175 MemExpr->getQualifierRange(),
7176 Fn,
7177 MemExpr->getMemberLoc(),
7178 Fn->getType(),
7179 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007180 } else {
7181 SourceLocation Loc = MemExpr->getMemberLoc();
7182 if (MemExpr->getQualifier())
7183 Loc = MemExpr->getQualifierRange().getBegin();
7184 Base = new (Context) CXXThisExpr(Loc,
7185 MemExpr->getBaseType(),
7186 /*isImplicit=*/true);
7187 }
John McCall2d74de92009-12-01 22:10:20 +00007188 } else
7189 Base = MemExpr->getBase()->Retain();
7190
7191 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007192 MemExpr->isArrow(),
7193 MemExpr->getQualifier(),
7194 MemExpr->getQualifierRange(),
7195 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007196 Found,
John McCall6b51f282009-11-23 01:53:49 +00007197 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007198 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007199 Fn->getType());
7200 }
7201
Douglas Gregor51c538b2009-11-20 19:42:02 +00007202 assert(false && "Invalid reference to overloaded function");
7203 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007204}
7205
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007206Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007207 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007208 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007209 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007210}
7211
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007212} // end namespace clang