blob: 4c48e6159c4b13da6d90b759e8dbcc08fc5b7019 [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
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000291static MakeDeductionFailureInfo(ASTContext &Context,
292 Sema::TemplateDeductionResult TDK,
Douglas Gregord09efd42010-05-08 20:07:26 +0000293 Sema::TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000294 OverloadCandidate::DeductionFailureInfo Result;
295 Result.Result = static_cast<unsigned>(TDK);
296 Result.Data = 0;
297 switch (TDK) {
298 case Sema::TDK_Success:
299 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000300 case Sema::TDK_TooManyArguments:
301 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000302 break;
303
304 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000305 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000306 Result.Data = Info.Param.getOpaqueValue();
307 break;
308
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000309 case Sema::TDK_Inconsistent:
310 case Sema::TDK_InconsistentQuals: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000311 // FIXME: Should allocate from normal heap so that we can free this later.
312 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000313 Saved->Param = Info.Param;
314 Saved->FirstArg = Info.FirstArg;
315 Saved->SecondArg = Info.SecondArg;
316 Result.Data = Saved;
317 break;
318 }
319
320 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000321 Result.Data = Info.take();
322 break;
323
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000324 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000325 case Sema::TDK_FailedOverloadResolution:
326 break;
327 }
328
329 return Result;
330}
John McCall0d1da222010-01-12 00:44:57 +0000331
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000332void OverloadCandidate::DeductionFailureInfo::Destroy() {
333 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
334 case Sema::TDK_Success:
335 case Sema::TDK_InstantiationDepth:
336 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000337 case Sema::TDK_TooManyArguments:
338 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000339 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000340 break;
341
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000342 case Sema::TDK_Inconsistent:
343 case Sema::TDK_InconsistentQuals:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000344 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000345 Data = 0;
346 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000347
348 case Sema::TDK_SubstitutionFailure:
349 // FIXME: Destroy the template arugment list?
350 Data = 0;
351 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000352
Douglas Gregor461761d2010-05-08 18:20:53 +0000353 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000354 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000355 case Sema::TDK_FailedOverloadResolution:
356 break;
357 }
358}
359
360TemplateParameter
361OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
362 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
363 case Sema::TDK_Success:
364 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000365 case Sema::TDK_TooManyArguments:
366 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000367 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000368 return TemplateParameter();
369
370 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000371 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000372 return TemplateParameter::getFromOpaqueValue(Data);
373
374 case Sema::TDK_Inconsistent:
375 case Sema::TDK_InconsistentQuals:
376 return static_cast<DFIParamWithArguments*>(Data)->Param;
377
378 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000379 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 case Sema::TDK_FailedOverloadResolution:
381 break;
382 }
383
384 return TemplateParameter();
385}
Douglas Gregord09efd42010-05-08 20:07:26 +0000386
387TemplateArgumentList *
388OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
389 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
390 case Sema::TDK_Success:
391 case Sema::TDK_InstantiationDepth:
392 case Sema::TDK_TooManyArguments:
393 case Sema::TDK_TooFewArguments:
394 case Sema::TDK_Incomplete:
395 case Sema::TDK_InvalidExplicitArguments:
396 case Sema::TDK_Inconsistent:
397 case Sema::TDK_InconsistentQuals:
398 return 0;
399
400 case Sema::TDK_SubstitutionFailure:
401 return static_cast<TemplateArgumentList*>(Data);
402
403 // Unhandled
404 case Sema::TDK_NonDeducedMismatch:
405 case Sema::TDK_FailedOverloadResolution:
406 break;
407 }
408
409 return 0;
410}
411
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000412const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
413 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
414 case Sema::TDK_Success:
415 case Sema::TDK_InstantiationDepth:
416 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000417 case Sema::TDK_TooManyArguments:
418 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000419 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000420 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000421 return 0;
422
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000423 case Sema::TDK_Inconsistent:
424 case Sema::TDK_InconsistentQuals:
425 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
426
Douglas Gregor461761d2010-05-08 18:20:53 +0000427 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000428 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429 case Sema::TDK_FailedOverloadResolution:
430 break;
431 }
432
433 return 0;
434}
435
436const TemplateArgument *
437OverloadCandidate::DeductionFailureInfo::getSecondArg() {
438 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
439 case Sema::TDK_Success:
440 case Sema::TDK_InstantiationDepth:
441 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000442 case Sema::TDK_TooManyArguments:
443 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000444 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000445 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000446 return 0;
447
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000448 case Sema::TDK_Inconsistent:
449 case Sema::TDK_InconsistentQuals:
450 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
451
Douglas Gregor461761d2010-05-08 18:20:53 +0000452 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000453 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 case Sema::TDK_FailedOverloadResolution:
455 break;
456 }
457
458 return 0;
459}
460
461void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 inherited::clear();
463 Functions.clear();
464}
465
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000467// overload of the declarations in Old. This routine returns false if
468// New and Old cannot be overloaded, e.g., if New has the same
469// signature as some function in Old (C++ 1.3.10) or if the Old
470// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000471// it does return false, MatchedDecl will point to the decl that New
472// cannot be overloaded with. This decl may be a UsingShadowDecl on
473// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474//
475// Example: Given the following input:
476//
477// void f(int, float); // #1
478// void f(int, int); // #2
479// int f(int, int); // #3
480//
481// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000482// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483//
John McCall3d988d92009-12-02 08:47:38 +0000484// When we process #2, Old contains only the FunctionDecl for #1. By
485// comparing the parameter types, we see that #1 and #2 are overloaded
486// (since they have different signatures), so this routine returns
487// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000488//
John McCall3d988d92009-12-02 08:47:38 +0000489// When we process #3, Old is an overload set containing #1 and #2. We
490// compare the signatures of #3 to #1 (they're overloaded, so we do
491// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
492// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493// signature), IsOverload returns false and MatchedDecl will be set to
494// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000495Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000496Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
497 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000498 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000499 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000500 NamedDecl *OldD = (*I)->getUnderlyingDecl();
501 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000502 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000503 Match = *I;
504 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 }
John McCall3d988d92009-12-02 08:47:38 +0000506 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000507 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000508 Match = *I;
509 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000510 }
John McCall84d87672009-12-10 09:41:52 +0000511 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
512 // We can overload with these, which can show up when doing
513 // redeclaration checks for UsingDecls.
514 assert(Old.getLookupKind() == LookupUsingDeclName);
515 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
516 // Optimistically assume that an unresolved using decl will
517 // overload; if it doesn't, we'll have to diagnose during
518 // template instantiation.
519 } else {
John McCall1f82f242009-11-18 22:49:29 +0000520 // (C++ 13p1):
521 // Only function declarations can be overloaded; object and type
522 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000523 Match = *I;
524 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000525 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000526 }
John McCall1f82f242009-11-18 22:49:29 +0000527
John McCalldaa3d6b2009-12-09 03:35:25 +0000528 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000529}
530
531bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
532 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
533 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
534
535 // C++ [temp.fct]p2:
536 // A function template can be overloaded with other function templates
537 // and with normal (non-template) functions.
538 if ((OldTemplate == 0) != (NewTemplate == 0))
539 return true;
540
541 // Is the function New an overload of the function Old?
542 QualType OldQType = Context.getCanonicalType(Old->getType());
543 QualType NewQType = Context.getCanonicalType(New->getType());
544
545 // Compare the signatures (C++ 1.3.10) of the two functions to
546 // determine whether they are overloads. If we find any mismatch
547 // in the signature, they are overloads.
548
549 // If either of these functions is a K&R-style function (no
550 // prototype), then we consider them to have matching signatures.
551 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
552 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
553 return false;
554
555 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
556 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
557
558 // The signature of a function includes the types of its
559 // parameters (C++ 1.3.10), which includes the presence or absence
560 // of the ellipsis; see C++ DR 357).
561 if (OldQType != NewQType &&
562 (OldType->getNumArgs() != NewType->getNumArgs() ||
563 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000564 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000565 return true;
566
567 // C++ [temp.over.link]p4:
568 // The signature of a function template consists of its function
569 // signature, its return type and its template parameter list. The names
570 // of the template parameters are significant only for establishing the
571 // relationship between the template parameters and the rest of the
572 // signature.
573 //
574 // We check the return type and template parameter lists for function
575 // templates first; the remaining checks follow.
576 if (NewTemplate &&
577 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
578 OldTemplate->getTemplateParameters(),
579 false, TPL_TemplateMatch) ||
580 OldType->getResultType() != NewType->getResultType()))
581 return true;
582
583 // If the function is a class member, its signature includes the
584 // cv-qualifiers (if any) on the function itself.
585 //
586 // As part of this, also check whether one of the member functions
587 // is static, in which case they are not overloads (C++
588 // 13.1p2). While not part of the definition of the signature,
589 // this check is important to determine whether these functions
590 // can be overloaded.
591 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
592 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
593 if (OldMethod && NewMethod &&
594 !OldMethod->isStatic() && !NewMethod->isStatic() &&
595 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
596 return true;
597
598 // The signatures match; this is not an overload.
599 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000600}
601
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000602/// TryImplicitConversion - Attempt to perform an implicit conversion
603/// from the given expression (Expr) to the given type (ToType). This
604/// function returns an implicit conversion sequence that can be used
605/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000606///
607/// void f(float f);
608/// void g(int i) { f(i); }
609///
610/// this routine would produce an implicit conversion sequence to
611/// describe the initialization of f from i, which will be a standard
612/// conversion sequence containing an lvalue-to-rvalue conversion (C++
613/// 4.1) followed by a floating-integral conversion (C++ 4.9).
614//
615/// Note that this routine only determines how the conversion can be
616/// performed; it does not actually perform the conversion. As such,
617/// it will not produce any diagnostics if no conversion is available,
618/// but will instead return an implicit conversion sequence of kind
619/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000620///
621/// If @p SuppressUserConversions, then user-defined conversions are
622/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000623/// If @p AllowExplicit, then explicit user-defined conversions are
624/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000625ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000626Sema::TryImplicitConversion(Expr* From, QualType ToType,
627 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000628 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000629 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000630 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000631 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000632 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000633 return ICS;
634 }
635
636 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000637 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000638 return ICS;
639 }
640
Douglas Gregor5ab11652010-04-17 22:01:05 +0000641 if (SuppressUserConversions) {
642 // C++ [over.ics.user]p4:
643 // A conversion of an expression of class type to the same class
644 // type is given Exact Match rank, and a conversion of an
645 // expression of class type to a base class of that type is
646 // given Conversion rank, in spite of the fact that a copy/move
647 // constructor (i.e., a user-defined conversion function) is
648 // called for those cases.
649 QualType FromType = From->getType();
650 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
651 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
652 IsDerivedFrom(FromType, ToType))) {
653 // We're not in the case above, so there is no conversion that
654 // we can perform.
655 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
656 return ICS;
657 }
658
659 ICS.setStandard();
660 ICS.Standard.setAsIdentityConversion();
661 ICS.Standard.setFromType(FromType);
662 ICS.Standard.setAllToTypes(ToType);
663
664 // We don't actually check at this point whether there is a valid
665 // copy/move constructor, since overloading just assumes that it
666 // exists. When we actually perform initialization, we'll find the
667 // appropriate constructor to copy the returned object, if needed.
668 ICS.Standard.CopyConstructor = 0;
669
670 // Determine whether this is considered a derived-to-base conversion.
671 if (!Context.hasSameUnqualifiedType(FromType, ToType))
672 ICS.Standard.Second = ICK_Derived_To_Base;
673
674 return ICS;
675 }
676
677 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000678 OverloadCandidateSet Conversions(From->getExprLoc());
679 OverloadingResult UserDefResult
680 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000681 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000682
683 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000684 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000685 // C++ [over.ics.user]p4:
686 // A conversion of an expression of class type to the same class
687 // type is given Exact Match rank, and a conversion of an
688 // expression of class type to a base class of that type is
689 // given Conversion rank, in spite of the fact that a copy
690 // constructor (i.e., a user-defined conversion function) is
691 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000692 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000693 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000694 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000695 = Context.getCanonicalType(From->getType().getUnqualifiedType());
696 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000697 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000698 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000699 // Turn this into a "standard" conversion sequence, so that it
700 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000701 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000702 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000703 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000704 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000705 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000706 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000707 ICS.Standard.Second = ICK_Derived_To_Base;
708 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000709 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000710
711 // C++ [over.best.ics]p4:
712 // However, when considering the argument of a user-defined
713 // conversion function that is a candidate by 13.3.1.3 when
714 // invoked for the copying of the temporary in the second step
715 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
716 // 13.3.1.6 in all cases, only standard conversion sequences and
717 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000718 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000719 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000720 }
John McCalle8c8cd22010-01-13 22:30:33 +0000721 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000722 ICS.setAmbiguous();
723 ICS.Ambiguous.setFromType(From->getType());
724 ICS.Ambiguous.setToType(ToType);
725 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
726 Cand != Conversions.end(); ++Cand)
727 if (Cand->Viable)
728 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000729 } else {
John McCall65eb8792010-02-25 01:37:24 +0000730 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000731 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000732
733 return ICS;
734}
735
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000736/// PerformImplicitConversion - Perform an implicit conversion of the
737/// expression From to the type ToType. Returns true if there was an
738/// error, false otherwise. The expression From is replaced with the
739/// converted expression. Flavor is the kind of conversion we're
740/// performing, used in the error message. If @p AllowExplicit,
741/// explicit user-defined conversions are permitted.
742bool
743Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
744 AssignmentAction Action, bool AllowExplicit) {
745 ImplicitConversionSequence ICS;
746 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
747}
748
749bool
750Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
751 AssignmentAction Action, bool AllowExplicit,
752 ImplicitConversionSequence& ICS) {
753 ICS = TryImplicitConversion(From, ToType,
754 /*SuppressUserConversions=*/false,
755 AllowExplicit,
756 /*InOverloadResolution=*/false);
757 return PerformImplicitConversion(From, ToType, ICS, Action);
758}
759
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000760/// \brief Determine whether the conversion from FromType to ToType is a valid
761/// conversion that strips "noreturn" off the nested function type.
762static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
763 QualType ToType, QualType &ResultTy) {
764 if (Context.hasSameUnqualifiedType(FromType, ToType))
765 return false;
766
767 // Strip the noreturn off the type we're converting from; noreturn can
768 // safely be removed.
769 FromType = Context.getNoReturnType(FromType, false);
770 if (!Context.hasSameUnqualifiedType(FromType, ToType))
771 return false;
772
773 ResultTy = FromType;
774 return true;
775}
776
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000777/// IsStandardConversion - Determines whether there is a standard
778/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
779/// expression From to the type ToType. Standard conversion sequences
780/// only consider non-class types; for conversions that involve class
781/// types, use TryImplicitConversion. If a conversion exists, SCS will
782/// contain the standard conversion sequence required to perform this
783/// conversion and this routine will return true. Otherwise, this
784/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000785bool
786Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000787 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000788 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789 QualType FromType = From->getType();
790
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000791 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000792 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000793 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000794 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000795 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000796 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000798 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000799 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000800 if (FromType->isRecordType() || ToType->isRecordType()) {
801 if (getLangOptions().CPlusPlus)
802 return false;
803
Mike Stump11289f42009-09-09 15:08:12 +0000804 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000805 }
806
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000807 // The first conversion can be an lvalue-to-rvalue conversion,
808 // array-to-pointer conversion, or function-to-pointer conversion
809 // (C++ 4p1).
810
Douglas Gregor980fb162010-04-29 18:24:40 +0000811 if (FromType == Context.OverloadTy) {
812 DeclAccessPair AccessPair;
813 if (FunctionDecl *Fn
814 = ResolveAddressOfOverloadedFunction(From, ToType, false,
815 AccessPair)) {
816 // We were able to resolve the address of the overloaded function,
817 // so we can convert to the type of that function.
818 FromType = Fn->getType();
819 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
820 if (!Method->isStatic()) {
821 Type *ClassType
822 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
823 FromType = Context.getMemberPointerType(FromType, ClassType);
824 }
825 }
826
827 // If the "from" expression takes the address of the overloaded
828 // function, update the type of the resulting expression accordingly.
829 if (FromType->getAs<FunctionType>())
830 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
831 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
832 FromType = Context.getPointerType(FromType);
833
834 // Check that we've computed the proper type after overload resolution.
835 assert(Context.hasSameType(FromType,
836 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
837 } else {
838 return false;
839 }
840 }
Mike Stump11289f42009-09-09 15:08:12 +0000841 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000842 // An lvalue (3.10) of a non-function, non-array type T can be
843 // converted to an rvalue.
844 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000845 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000846 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000847 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000848 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000849
850 // If T is a non-class type, the type of the rvalue is the
851 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000852 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
853 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000854 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000855 } else if (FromType->isArrayType()) {
856 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000857 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858
859 // An lvalue or rvalue of type "array of N T" or "array of unknown
860 // bound of T" can be converted to an rvalue of type "pointer to
861 // T" (C++ 4.2p1).
862 FromType = Context.getArrayDecayedType(FromType);
863
864 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
865 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000866 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000867
868 // For the purpose of ranking in overload resolution
869 // (13.3.3.1.1), this conversion is considered an
870 // array-to-pointer conversion followed by a qualification
871 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000872 SCS.Second = ICK_Identity;
873 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000874 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000875 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000876 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000877 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
878 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000879 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880
881 // An lvalue of function type T can be converted to an rvalue of
882 // type "pointer to T." The result is a pointer to the
883 // function. (C++ 4.3p1).
884 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000885 } else {
886 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000887 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000888 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000889 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000890
891 // The second conversion can be an integral promotion, floating
892 // point promotion, integral conversion, floating point conversion,
893 // floating-integral conversion, pointer conversion,
894 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000895 // For overloading in C, this can also be a "compatible-type"
896 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000897 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000898 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000899 // The unqualified versions of the types are the same: there's no
900 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000901 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000902 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000903 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000904 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000905 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000906 } else if (IsFloatingPointPromotion(FromType, ToType)) {
907 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000908 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000909 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000910 } else if (IsComplexPromotion(FromType, ToType)) {
911 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000912 SCS.Second = ICK_Complex_Promotion;
913 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000914 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000915 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000916 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000917 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000918 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000919 } else if (FromType->isComplexType() && ToType->isComplexType()) {
920 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000921 SCS.Second = ICK_Complex_Conversion;
922 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000923 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
924 (ToType->isComplexType() && FromType->isArithmeticType())) {
925 // Complex-real conversions (C99 6.3.1.7)
926 SCS.Second = ICK_Complex_Real;
927 FromType = ToType.getUnqualifiedType();
928 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
929 // Floating point conversions (C++ 4.8).
930 SCS.Second = ICK_Floating_Conversion;
931 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000932 } else if ((FromType->isFloatingType() &&
933 ToType->isIntegralType() && (!ToType->isBooleanType() &&
934 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000935 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000936 ToType->isFloatingType())) {
937 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000938 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000939 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000940 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
941 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000942 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000943 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000944 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000945 } else if (IsMemberPointerConversion(From, FromType, ToType,
946 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000947 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000948 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000949 } else if (ToType->isBooleanType() &&
950 (FromType->isArithmeticType() ||
951 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000952 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000953 FromType->isBlockPointerType() ||
954 FromType->isMemberPointerType() ||
955 FromType->isNullPtrType())) {
956 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000957 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000958 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000959 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000960 Context.typesAreCompatible(ToType, FromType)) {
961 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000962 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000963 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
964 // Treat a conversion that strips "noreturn" as an identity conversion.
965 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000966 } else {
967 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000968 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000970 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000971
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000972 QualType CanonFrom;
973 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000975 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000976 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000977 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000978 CanonFrom = Context.getCanonicalType(FromType);
979 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000980 } else {
981 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000982 SCS.Third = ICK_Identity;
983
Mike Stump11289f42009-09-09 15:08:12 +0000984 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000985 // [...] Any difference in top-level cv-qualification is
986 // subsumed by the initialization itself and does not constitute
987 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000988 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000989 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000990 if (CanonFrom.getLocalUnqualifiedType()
991 == CanonTo.getLocalUnqualifiedType() &&
992 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000993 FromType = ToType;
994 CanonFrom = CanonTo;
995 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000996 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000997 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000998
999 // If we have not converted the argument type to the parameter type,
1000 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001001 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001002 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001003
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001004 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001005}
1006
1007/// IsIntegralPromotion - Determines whether the conversion from the
1008/// expression From (whose potentially-adjusted type is FromType) to
1009/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1010/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001011bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001012 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001013 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001014 if (!To) {
1015 return false;
1016 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001017
1018 // An rvalue of type char, signed char, unsigned char, short int, or
1019 // unsigned short int can be converted to an rvalue of type int if
1020 // int can represent all the values of the source type; otherwise,
1021 // the source rvalue can be converted to an rvalue of type unsigned
1022 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001023 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1024 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001025 if (// We can promote any signed, promotable integer type to an int
1026 (FromType->isSignedIntegerType() ||
1027 // We can promote any unsigned integer type whose size is
1028 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001029 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001030 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001031 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001032 }
1033
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001034 return To->getKind() == BuiltinType::UInt;
1035 }
1036
1037 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1038 // can be converted to an rvalue of the first of the following types
1039 // that can represent all the values of its underlying type: int,
1040 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001041
1042 // We pre-calculate the promotion type for enum types.
1043 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1044 if (ToType->isIntegerType())
1045 return Context.hasSameUnqualifiedType(ToType,
1046 FromEnumType->getDecl()->getPromotionType());
1047
1048 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001049 // Determine whether the type we're converting from is signed or
1050 // unsigned.
1051 bool FromIsSigned;
1052 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001053
1054 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1055 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001056
1057 // The types we'll try to promote to, in the appropriate
1058 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001059 QualType PromoteTypes[6] = {
1060 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001061 Context.LongTy, Context.UnsignedLongTy ,
1062 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001063 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001064 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001065 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1066 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001067 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001068 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1069 // We found the type that we can promote to. If this is the
1070 // type we wanted, we have a promotion. Otherwise, no
1071 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001072 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073 }
1074 }
1075 }
1076
1077 // An rvalue for an integral bit-field (9.6) can be converted to an
1078 // rvalue of type int if int can represent all the values of the
1079 // bit-field; otherwise, it can be converted to unsigned int if
1080 // unsigned int can represent all the values of the bit-field. If
1081 // the bit-field is larger yet, no integral promotion applies to
1082 // it. If the bit-field has an enumerated type, it is treated as any
1083 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001084 // FIXME: We should delay checking of bit-fields until we actually perform the
1085 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001086 using llvm::APSInt;
1087 if (From)
1088 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001089 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +00001090 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
1091 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1092 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1093 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001094
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001095 // Are we promoting to an int from a bitfield that fits in an int?
1096 if (BitWidth < ToSize ||
1097 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1098 return To->getKind() == BuiltinType::Int;
1099 }
Mike Stump11289f42009-09-09 15:08:12 +00001100
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001101 // Are we promoting to an unsigned int from an unsigned bitfield
1102 // that fits into an unsigned int?
1103 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1104 return To->getKind() == BuiltinType::UInt;
1105 }
Mike Stump11289f42009-09-09 15:08:12 +00001106
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001107 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001108 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001109 }
Mike Stump11289f42009-09-09 15:08:12 +00001110
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111 // An rvalue of type bool can be converted to an rvalue of type int,
1112 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001113 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001114 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001115 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001116
1117 return false;
1118}
1119
1120/// IsFloatingPointPromotion - Determines whether the conversion from
1121/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1122/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001123bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124 /// An rvalue of type float can be converted to an rvalue of type
1125 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001126 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1127 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128 if (FromBuiltin->getKind() == BuiltinType::Float &&
1129 ToBuiltin->getKind() == BuiltinType::Double)
1130 return true;
1131
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001132 // C99 6.3.1.5p1:
1133 // When a float is promoted to double or long double, or a
1134 // double is promoted to long double [...].
1135 if (!getLangOptions().CPlusPlus &&
1136 (FromBuiltin->getKind() == BuiltinType::Float ||
1137 FromBuiltin->getKind() == BuiltinType::Double) &&
1138 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1139 return true;
1140 }
1141
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142 return false;
1143}
1144
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001145/// \brief Determine if a conversion is a complex promotion.
1146///
1147/// A complex promotion is defined as a complex -> complex conversion
1148/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001149/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001150bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001151 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001152 if (!FromComplex)
1153 return false;
1154
John McCall9dd450b2009-09-21 23:43:11 +00001155 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001156 if (!ToComplex)
1157 return false;
1158
1159 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001160 ToComplex->getElementType()) ||
1161 IsIntegralPromotion(0, FromComplex->getElementType(),
1162 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001163}
1164
Douglas Gregor237f96c2008-11-26 23:31:11 +00001165/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1166/// the pointer type FromPtr to a pointer to type ToPointee, with the
1167/// same type qualifiers as FromPtr has on its pointee type. ToType,
1168/// if non-empty, will be a pointer to ToType that may or may not have
1169/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001170static QualType
1171BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001172 QualType ToPointee, QualType ToType,
1173 ASTContext &Context) {
1174 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1175 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001176 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001177
1178 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001179 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001180 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001181 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +00001182 return ToType;
1183
1184 // Build a pointer to ToPointee. It has the right qualifiers
1185 // already.
1186 return Context.getPointerType(ToPointee);
1187 }
1188
1189 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001190 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001191 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1192 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001193}
1194
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001195/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1196/// the FromType, which is an objective-c pointer, to ToType, which may or may
1197/// not have the right set of qualifiers.
1198static QualType
1199BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1200 QualType ToType,
1201 ASTContext &Context) {
1202 QualType CanonFromType = Context.getCanonicalType(FromType);
1203 QualType CanonToType = Context.getCanonicalType(ToType);
1204 Qualifiers Quals = CanonFromType.getQualifiers();
1205
1206 // Exact qualifier match -> return the pointer type we're converting to.
1207 if (CanonToType.getLocalQualifiers() == Quals)
1208 return ToType;
1209
1210 // Just build a canonical type that has the right qualifiers.
1211 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1212}
1213
Mike Stump11289f42009-09-09 15:08:12 +00001214static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001215 bool InOverloadResolution,
1216 ASTContext &Context) {
1217 // Handle value-dependent integral null pointer constants correctly.
1218 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1219 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1220 Expr->getType()->isIntegralType())
1221 return !InOverloadResolution;
1222
Douglas Gregor56751b52009-09-25 04:25:58 +00001223 return Expr->isNullPointerConstant(Context,
1224 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1225 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001226}
Mike Stump11289f42009-09-09 15:08:12 +00001227
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228/// IsPointerConversion - Determines whether the conversion of the
1229/// expression From, which has the (possibly adjusted) type FromType,
1230/// can be converted to the type ToType via a pointer conversion (C++
1231/// 4.10). If so, returns true and places the converted type (that
1232/// might differ from ToType in its cv-qualifiers at some level) into
1233/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001234///
Douglas Gregora29dc052008-11-27 01:19:21 +00001235/// This routine also supports conversions to and from block pointers
1236/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1237/// pointers to interfaces. FIXME: Once we've determined the
1238/// appropriate overloading rules for Objective-C, we may want to
1239/// split the Objective-C checks into a different routine; however,
1240/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001241/// conversions, so for now they live here. IncompatibleObjC will be
1242/// set if the conversion is an allowed Objective-C conversion that
1243/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001244bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001245 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001246 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001247 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001248 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001249 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1250 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001251
Mike Stump11289f42009-09-09 15:08:12 +00001252 // Conversion from a null pointer constant to any Objective-C pointer type.
1253 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001254 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001255 ConvertedType = ToType;
1256 return true;
1257 }
1258
Douglas Gregor231d1c62008-11-27 00:15:41 +00001259 // Blocks: Block pointers can be converted to void*.
1260 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001261 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001262 ConvertedType = ToType;
1263 return true;
1264 }
1265 // Blocks: A null pointer constant can be converted to a block
1266 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001267 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001268 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001269 ConvertedType = ToType;
1270 return true;
1271 }
1272
Sebastian Redl576fd422009-05-10 18:38:11 +00001273 // If the left-hand-side is nullptr_t, the right side can be a null
1274 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001275 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001276 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001277 ConvertedType = ToType;
1278 return true;
1279 }
1280
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001281 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001282 if (!ToTypePtr)
1283 return false;
1284
1285 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001286 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001287 ConvertedType = ToType;
1288 return true;
1289 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001290
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001291 // Beyond this point, both types need to be pointers
1292 // , including objective-c pointers.
1293 QualType ToPointeeType = ToTypePtr->getPointeeType();
1294 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1295 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1296 ToType, Context);
1297 return true;
1298
1299 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001300 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001301 if (!FromTypePtr)
1302 return false;
1303
1304 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001305
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001306 // An rvalue of type "pointer to cv T," where T is an object type,
1307 // can be converted to an rvalue of type "pointer to cv void" (C++
1308 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001309 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001310 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001311 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001312 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001313 return true;
1314 }
1315
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001316 // When we're overloading in C, we allow a special kind of pointer
1317 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001318 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001319 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001320 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001321 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001322 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001323 return true;
1324 }
1325
Douglas Gregor5c407d92008-10-23 00:40:37 +00001326 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001327 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001328 // An rvalue of type "pointer to cv D," where D is a class type,
1329 // can be converted to an rvalue of type "pointer to cv B," where
1330 // B is a base class (clause 10) of D. If B is an inaccessible
1331 // (clause 11) or ambiguous (10.2) base class of D, a program that
1332 // necessitates this conversion is ill-formed. The result of the
1333 // conversion is a pointer to the base class sub-object of the
1334 // derived class object. The null pointer value is converted to
1335 // the null pointer value of the destination type.
1336 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001337 // Note that we do not check for ambiguity or inaccessibility
1338 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001339 if (getLangOptions().CPlusPlus &&
1340 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001341 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001342 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001343 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001344 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001345 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001346 ToType, Context);
1347 return true;
1348 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001349
Douglas Gregora119f102008-12-19 19:13:09 +00001350 return false;
1351}
1352
1353/// isObjCPointerConversion - Determines whether this is an
1354/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1355/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001356bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001357 QualType& ConvertedType,
1358 bool &IncompatibleObjC) {
1359 if (!getLangOptions().ObjC1)
1360 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001361
Steve Naroff7cae42b2009-07-10 23:34:53 +00001362 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001363 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001364 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001365 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001366
Steve Naroff7cae42b2009-07-10 23:34:53 +00001367 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001368 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001369 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001370 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001371 ConvertedType = ToType;
1372 return true;
1373 }
1374 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001375 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001376 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001377 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001378 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001379 ConvertedType = ToType;
1380 return true;
1381 }
1382 // Objective C++: We're able to convert from a pointer to an
1383 // interface to a pointer to a different interface.
1384 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001385 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1386 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1387 if (getLangOptions().CPlusPlus && LHS && RHS &&
1388 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1389 FromObjCPtr->getPointeeType()))
1390 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001391 ConvertedType = ToType;
1392 return true;
1393 }
1394
1395 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1396 // Okay: this is some kind of implicit downcast of Objective-C
1397 // interfaces, which is permitted. However, we're going to
1398 // complain about it.
1399 IncompatibleObjC = true;
1400 ConvertedType = FromType;
1401 return true;
1402 }
Mike Stump11289f42009-09-09 15:08:12 +00001403 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001404 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001405 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001406 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001407 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001408 else if (const BlockPointerType *ToBlockPtr =
1409 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001410 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001411 // to a block pointer type.
1412 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1413 ConvertedType = ToType;
1414 return true;
1415 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001416 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001417 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001418 else if (FromType->getAs<BlockPointerType>() &&
1419 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1420 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001421 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001422 ConvertedType = ToType;
1423 return true;
1424 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001425 else
Douglas Gregora119f102008-12-19 19:13:09 +00001426 return false;
1427
Douglas Gregor033f56d2008-12-23 00:53:59 +00001428 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001429 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001430 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001431 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001432 FromPointeeType = FromBlockPtr->getPointeeType();
1433 else
Douglas Gregora119f102008-12-19 19:13:09 +00001434 return false;
1435
Douglas Gregora119f102008-12-19 19:13:09 +00001436 // If we have pointers to pointers, recursively check whether this
1437 // is an Objective-C conversion.
1438 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1439 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1440 IncompatibleObjC)) {
1441 // We always complain about this conversion.
1442 IncompatibleObjC = true;
1443 ConvertedType = ToType;
1444 return true;
1445 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001446 // Allow conversion of pointee being objective-c pointer to another one;
1447 // as in I* to id.
1448 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1449 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1450 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1451 IncompatibleObjC)) {
1452 ConvertedType = ToType;
1453 return true;
1454 }
1455
Douglas Gregor033f56d2008-12-23 00:53:59 +00001456 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001457 // differences in the argument and result types are in Objective-C
1458 // pointer conversions. If so, we permit the conversion (but
1459 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001460 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001461 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001462 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001463 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001464 if (FromFunctionType && ToFunctionType) {
1465 // If the function types are exactly the same, this isn't an
1466 // Objective-C pointer conversion.
1467 if (Context.getCanonicalType(FromPointeeType)
1468 == Context.getCanonicalType(ToPointeeType))
1469 return false;
1470
1471 // Perform the quick checks that will tell us whether these
1472 // function types are obviously different.
1473 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1474 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1475 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1476 return false;
1477
1478 bool HasObjCConversion = false;
1479 if (Context.getCanonicalType(FromFunctionType->getResultType())
1480 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1481 // Okay, the types match exactly. Nothing to do.
1482 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1483 ToFunctionType->getResultType(),
1484 ConvertedType, IncompatibleObjC)) {
1485 // Okay, we have an Objective-C pointer conversion.
1486 HasObjCConversion = true;
1487 } else {
1488 // Function types are too different. Abort.
1489 return false;
1490 }
Mike Stump11289f42009-09-09 15:08:12 +00001491
Douglas Gregora119f102008-12-19 19:13:09 +00001492 // Check argument types.
1493 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1494 ArgIdx != NumArgs; ++ArgIdx) {
1495 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1496 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1497 if (Context.getCanonicalType(FromArgType)
1498 == Context.getCanonicalType(ToArgType)) {
1499 // Okay, the types match exactly. Nothing to do.
1500 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1501 ConvertedType, IncompatibleObjC)) {
1502 // Okay, we have an Objective-C pointer conversion.
1503 HasObjCConversion = true;
1504 } else {
1505 // Argument types are too different. Abort.
1506 return false;
1507 }
1508 }
1509
1510 if (HasObjCConversion) {
1511 // We had an Objective-C conversion. Allow this pointer
1512 // conversion, but complain about it.
1513 ConvertedType = ToType;
1514 IncompatibleObjC = true;
1515 return true;
1516 }
1517 }
1518
Sebastian Redl72b597d2009-01-25 19:43:20 +00001519 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001520}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001521
1522/// FunctionArgTypesAreEqual - This routine checks two function proto types
1523/// for equlity of their argument types. Caller has already checked that
1524/// they have same number of arguments. This routine assumes that Objective-C
1525/// pointer types which only differ in their protocol qualifiers are equal.
1526bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1527 FunctionProtoType* NewType){
1528 if (!getLangOptions().ObjC1)
1529 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1530 NewType->arg_type_begin());
1531
1532 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1533 N = NewType->arg_type_begin(),
1534 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1535 QualType ToType = (*O);
1536 QualType FromType = (*N);
1537 if (ToType != FromType) {
1538 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1539 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001540 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1541 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1542 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1543 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001544 continue;
1545 }
John McCall8b07ec22010-05-15 11:32:37 +00001546 else if (const ObjCObjectPointerType *PTTo =
1547 ToType->getAs<ObjCObjectPointerType>()) {
1548 if (const ObjCObjectPointerType *PTFr =
1549 FromType->getAs<ObjCObjectPointerType>())
1550 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1551 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001552 }
1553 return false;
1554 }
1555 }
1556 return true;
1557}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558
Douglas Gregor39c16d42008-10-24 04:54:22 +00001559/// CheckPointerConversion - Check the pointer conversion from the
1560/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001561/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001562/// conversions for which IsPointerConversion has already returned
1563/// true. It returns true and produces a diagnostic if there was an
1564/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001565bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001566 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001567 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001568 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001569 QualType FromType = From->getType();
1570
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001571 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1572 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001573 QualType FromPointeeType = FromPtrType->getPointeeType(),
1574 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001575
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001576 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1577 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001578 // We must have a derived-to-base conversion. Check an
1579 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001580 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1581 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001582 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001583 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001584 return true;
1585
1586 // The conversion was successful.
1587 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001588 }
1589 }
Mike Stump11289f42009-09-09 15:08:12 +00001590 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001591 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001592 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001593 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001594 // Objective-C++ conversions are always okay.
1595 // FIXME: We should have a different class of conversions for the
1596 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001597 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001598 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001599
Steve Naroff7cae42b2009-07-10 23:34:53 +00001600 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001601 return false;
1602}
1603
Sebastian Redl72b597d2009-01-25 19:43:20 +00001604/// IsMemberPointerConversion - Determines whether the conversion of the
1605/// expression From, which has the (possibly adjusted) type FromType, can be
1606/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1607/// If so, returns true and places the converted type (that might differ from
1608/// ToType in its cv-qualifiers at some level) into ConvertedType.
1609bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001610 QualType ToType,
1611 bool InOverloadResolution,
1612 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001613 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001614 if (!ToTypePtr)
1615 return false;
1616
1617 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001618 if (From->isNullPointerConstant(Context,
1619 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1620 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001621 ConvertedType = ToType;
1622 return true;
1623 }
1624
1625 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001626 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001627 if (!FromTypePtr)
1628 return false;
1629
1630 // A pointer to member of B can be converted to a pointer to member of D,
1631 // where D is derived from B (C++ 4.11p2).
1632 QualType FromClass(FromTypePtr->getClass(), 0);
1633 QualType ToClass(ToTypePtr->getClass(), 0);
1634 // FIXME: What happens when these are dependent? Is this function even called?
1635
1636 if (IsDerivedFrom(ToClass, FromClass)) {
1637 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1638 ToClass.getTypePtr());
1639 return true;
1640 }
1641
1642 return false;
1643}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001644
Sebastian Redl72b597d2009-01-25 19:43:20 +00001645/// CheckMemberPointerConversion - Check the member pointer conversion from the
1646/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001647/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001648/// for which IsMemberPointerConversion has already returned true. It returns
1649/// true and produces a diagnostic if there was an error, or returns false
1650/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001651bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001652 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001653 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001654 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001655 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001656 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001657 if (!FromPtrType) {
1658 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001659 assert(From->isNullPointerConstant(Context,
1660 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001661 "Expr must be null pointer constant!");
1662 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001663 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001664 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001665
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001666 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001667 assert(ToPtrType && "No member pointer cast has a target type "
1668 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001669
Sebastian Redled8f2002009-01-28 18:33:18 +00001670 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1671 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001672
Sebastian Redled8f2002009-01-28 18:33:18 +00001673 // FIXME: What about dependent types?
1674 assert(FromClass->isRecordType() && "Pointer into non-class.");
1675 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001676
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001677 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001678 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001679 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1680 assert(DerivationOkay &&
1681 "Should not have been called if derivation isn't OK.");
1682 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001683
Sebastian Redled8f2002009-01-28 18:33:18 +00001684 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1685 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001686 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1687 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1688 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1689 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001690 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001691
Douglas Gregor89ee6822009-02-28 01:32:25 +00001692 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001693 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1694 << FromClass << ToClass << QualType(VBase, 0)
1695 << From->getSourceRange();
1696 return true;
1697 }
1698
John McCall5b0829a2010-02-10 09:31:12 +00001699 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001700 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1701 Paths.front(),
1702 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001703
Anders Carlssond7923c62009-08-22 23:33:40 +00001704 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001705 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001706 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001707 return false;
1708}
1709
Douglas Gregor9a657932008-10-21 23:43:52 +00001710/// IsQualificationConversion - Determines whether the conversion from
1711/// an rvalue of type FromType to ToType is a qualification conversion
1712/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001713bool
1714Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001715 FromType = Context.getCanonicalType(FromType);
1716 ToType = Context.getCanonicalType(ToType);
1717
1718 // If FromType and ToType are the same type, this is not a
1719 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001720 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001721 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001722
Douglas Gregor9a657932008-10-21 23:43:52 +00001723 // (C++ 4.4p4):
1724 // A conversion can add cv-qualifiers at levels other than the first
1725 // in multi-level pointers, subject to the following rules: [...]
1726 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001727 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001728 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001729 // Within each iteration of the loop, we check the qualifiers to
1730 // determine if this still looks like a qualification
1731 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001732 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001733 // until there are no more pointers or pointers-to-members left to
1734 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001735 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001736
1737 // -- for every j > 0, if const is in cv 1,j then const is in cv
1738 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001739 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001740 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001741
Douglas Gregor9a657932008-10-21 23:43:52 +00001742 // -- if the cv 1,j and cv 2,j are different, then const is in
1743 // every cv for 0 < k < j.
1744 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001745 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001746 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001747
Douglas Gregor9a657932008-10-21 23:43:52 +00001748 // Keep track of whether all prior cv-qualifiers in the "to" type
1749 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001750 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001751 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001752 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001753
1754 // We are left with FromType and ToType being the pointee types
1755 // after unwrapping the original FromType and ToType the same number
1756 // of types. If we unwrapped any pointers, and if FromType and
1757 // ToType have the same unqualified type (since we checked
1758 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001759 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001760}
1761
Douglas Gregor576e98c2009-01-30 23:27:23 +00001762/// Determines whether there is a user-defined conversion sequence
1763/// (C++ [over.ics.user]) that converts expression From to the type
1764/// ToType. If such a conversion exists, User will contain the
1765/// user-defined conversion sequence that performs such a conversion
1766/// and this routine will return true. Otherwise, this routine returns
1767/// false and User is unspecified.
1768///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001769/// \param AllowExplicit true if the conversion should consider C++0x
1770/// "explicit" conversion functions as well as non-explicit conversion
1771/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001772OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1773 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001774 OverloadCandidateSet& CandidateSet,
1775 bool AllowExplicit) {
1776 // Whether we will only visit constructors.
1777 bool ConstructorsOnly = false;
1778
1779 // If the type we are conversion to is a class type, enumerate its
1780 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001781 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001782 // C++ [over.match.ctor]p1:
1783 // When objects of class type are direct-initialized (8.5), or
1784 // copy-initialized from an expression of the same or a
1785 // derived class type (8.5), overload resolution selects the
1786 // constructor. [...] For copy-initialization, the candidate
1787 // functions are all the converting constructors (12.3.1) of
1788 // that class. The argument list is the expression-list within
1789 // the parentheses of the initializer.
1790 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1791 (From->getType()->getAs<RecordType>() &&
1792 IsDerivedFrom(From->getType(), ToType)))
1793 ConstructorsOnly = true;
1794
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001795 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1796 // We're not going to find any constructors.
1797 } else if (CXXRecordDecl *ToRecordDecl
1798 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001799 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001800 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001801 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001802 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001803 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001804 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001805 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001806 NamedDecl *D = *Con;
1807 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1808
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001809 // Find the constructor (which may be a template).
1810 CXXConstructorDecl *Constructor = 0;
1811 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001812 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001813 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001814 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001815 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1816 else
John McCalla0296f72010-03-19 07:35:19 +00001817 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001818
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001819 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001820 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001821 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001822 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001823 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001824 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001825 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001826 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001827 // Allow one user-defined conversion when user specifies a
1828 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001829 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001830 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001831 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001832 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001833 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001834 }
1835 }
1836
Douglas Gregor5ab11652010-04-17 22:01:05 +00001837 // Enumerate conversion functions, if we're allowed to.
1838 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001839 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001840 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001841 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001842 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001843 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001844 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001845 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1846 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001847 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001848 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001849 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001850 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001851 DeclAccessPair FoundDecl = I.getPair();
1852 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001853 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1854 if (isa<UsingShadowDecl>(D))
1855 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1856
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001857 CXXConversionDecl *Conv;
1858 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001859 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1860 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001861 else
John McCallda4458e2010-03-31 01:36:47 +00001862 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001863
1864 if (AllowExplicit || !Conv->isExplicit()) {
1865 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001866 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001867 ActingContext, From, ToType,
1868 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001869 else
John McCalla0296f72010-03-19 07:35:19 +00001870 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001871 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001872 }
1873 }
1874 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001875 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001876
1877 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001878 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001879 case OR_Success:
1880 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001881 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001882 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1883 // C++ [over.ics.user]p1:
1884 // If the user-defined conversion is specified by a
1885 // constructor (12.3.1), the initial standard conversion
1886 // sequence converts the source type to the type required by
1887 // the argument of the constructor.
1888 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001889 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001890 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001891 User.EllipsisConversion = true;
1892 else {
1893 User.Before = Best->Conversions[0].Standard;
1894 User.EllipsisConversion = false;
1895 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001896 User.ConversionFunction = Constructor;
1897 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001898 User.After.setFromType(
1899 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001900 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001901 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001902 } else if (CXXConversionDecl *Conversion
1903 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1904 // C++ [over.ics.user]p1:
1905 //
1906 // [...] If the user-defined conversion is specified by a
1907 // conversion function (12.3.2), the initial standard
1908 // conversion sequence converts the source type to the
1909 // implicit object parameter of the conversion function.
1910 User.Before = Best->Conversions[0].Standard;
1911 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001912 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001913
1914 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001915 // The second standard conversion sequence converts the
1916 // result of the user-defined conversion to the target type
1917 // for the sequence. Since an implicit conversion sequence
1918 // is an initialization, the special rules for
1919 // initialization by user-defined conversion apply when
1920 // selecting the best user-defined conversion for a
1921 // user-defined conversion sequence (see 13.3.3 and
1922 // 13.3.3.1).
1923 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001924 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001925 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001926 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001927 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001928 }
Mike Stump11289f42009-09-09 15:08:12 +00001929
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001930 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001931 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001932 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001933 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001934 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001935
1936 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001937 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001938 }
1939
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001940 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001941}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001942
1943bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001944Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001945 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001946 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001947 OverloadingResult OvResult =
1948 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001949 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001950 if (OvResult == OR_Ambiguous)
1951 Diag(From->getSourceRange().getBegin(),
1952 diag::err_typecheck_ambiguous_condition)
1953 << From->getType() << ToType << From->getSourceRange();
1954 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1955 Diag(From->getSourceRange().getBegin(),
1956 diag::err_typecheck_nonviable_condition)
1957 << From->getType() << ToType << From->getSourceRange();
1958 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001959 return false;
John McCallad907772010-01-12 07:18:19 +00001960 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001961 return true;
1962}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001963
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001964/// CompareImplicitConversionSequences - Compare two implicit
1965/// conversion sequences to determine whether one is better than the
1966/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001967ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001968Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1969 const ImplicitConversionSequence& ICS2)
1970{
1971 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1972 // conversion sequences (as defined in 13.3.3.1)
1973 // -- a standard conversion sequence (13.3.3.1.1) is a better
1974 // conversion sequence than a user-defined conversion sequence or
1975 // an ellipsis conversion sequence, and
1976 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1977 // conversion sequence than an ellipsis conversion sequence
1978 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001979 //
John McCall0d1da222010-01-12 00:44:57 +00001980 // C++0x [over.best.ics]p10:
1981 // For the purpose of ranking implicit conversion sequences as
1982 // described in 13.3.3.2, the ambiguous conversion sequence is
1983 // treated as a user-defined sequence that is indistinguishable
1984 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00001985 if (ICS1.getKindRank() < ICS2.getKindRank())
1986 return ImplicitConversionSequence::Better;
1987 else if (ICS2.getKindRank() < ICS1.getKindRank())
1988 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001989
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00001990 // The following checks require both conversion sequences to be of
1991 // the same kind.
1992 if (ICS1.getKind() != ICS2.getKind())
1993 return ImplicitConversionSequence::Indistinguishable;
1994
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001995 // Two implicit conversion sequences of the same form are
1996 // indistinguishable conversion sequences unless one of the
1997 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001998 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001999 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002000 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002001 // User-defined conversion sequence U1 is a better conversion
2002 // sequence than another user-defined conversion sequence U2 if
2003 // they contain the same user-defined conversion function or
2004 // constructor and if the second standard conversion sequence of
2005 // U1 is better than the second standard conversion sequence of
2006 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002007 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002008 ICS2.UserDefined.ConversionFunction)
2009 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2010 ICS2.UserDefined.After);
2011 }
2012
2013 return ImplicitConversionSequence::Indistinguishable;
2014}
2015
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002016// Per 13.3.3.2p3, compare the given standard conversion sequences to
2017// determine if one is a proper subset of the other.
2018static ImplicitConversionSequence::CompareKind
2019compareStandardConversionSubsets(ASTContext &Context,
2020 const StandardConversionSequence& SCS1,
2021 const StandardConversionSequence& SCS2) {
2022 ImplicitConversionSequence::CompareKind Result
2023 = ImplicitConversionSequence::Indistinguishable;
2024
2025 if (SCS1.Second != SCS2.Second) {
2026 if (SCS1.Second == ICK_Identity)
2027 Result = ImplicitConversionSequence::Better;
2028 else if (SCS2.Second == ICK_Identity)
2029 Result = ImplicitConversionSequence::Worse;
2030 else
2031 return ImplicitConversionSequence::Indistinguishable;
2032 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
2033 return ImplicitConversionSequence::Indistinguishable;
2034
2035 if (SCS1.Third == SCS2.Third) {
2036 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2037 : ImplicitConversionSequence::Indistinguishable;
2038 }
2039
2040 if (SCS1.Third == ICK_Identity)
2041 return Result == ImplicitConversionSequence::Worse
2042 ? ImplicitConversionSequence::Indistinguishable
2043 : ImplicitConversionSequence::Better;
2044
2045 if (SCS2.Third == ICK_Identity)
2046 return Result == ImplicitConversionSequence::Better
2047 ? ImplicitConversionSequence::Indistinguishable
2048 : ImplicitConversionSequence::Worse;
2049
2050 return ImplicitConversionSequence::Indistinguishable;
2051}
2052
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002053/// CompareStandardConversionSequences - Compare two standard
2054/// conversion sequences to determine whether one is better than the
2055/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002056ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002057Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2058 const StandardConversionSequence& SCS2)
2059{
2060 // Standard conversion sequence S1 is a better conversion sequence
2061 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2062
2063 // -- S1 is a proper subsequence of S2 (comparing the conversion
2064 // sequences in the canonical form defined by 13.3.3.1.1,
2065 // excluding any Lvalue Transformation; the identity conversion
2066 // sequence is considered to be a subsequence of any
2067 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002068 if (ImplicitConversionSequence::CompareKind CK
2069 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2070 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002071
2072 // -- the rank of S1 is better than the rank of S2 (by the rules
2073 // defined below), or, if not that,
2074 ImplicitConversionRank Rank1 = SCS1.getRank();
2075 ImplicitConversionRank Rank2 = SCS2.getRank();
2076 if (Rank1 < Rank2)
2077 return ImplicitConversionSequence::Better;
2078 else if (Rank2 < Rank1)
2079 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002080
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002081 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2082 // are indistinguishable unless one of the following rules
2083 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002084
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002085 // A conversion that is not a conversion of a pointer, or
2086 // pointer to member, to bool is better than another conversion
2087 // that is such a conversion.
2088 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2089 return SCS2.isPointerConversionToBool()
2090 ? ImplicitConversionSequence::Better
2091 : ImplicitConversionSequence::Worse;
2092
Douglas Gregor5c407d92008-10-23 00:40:37 +00002093 // C++ [over.ics.rank]p4b2:
2094 //
2095 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002096 // conversion of B* to A* is better than conversion of B* to
2097 // void*, and conversion of A* to void* is better than conversion
2098 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002099 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002100 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002101 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002102 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002103 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2104 // Exactly one of the conversion sequences is a conversion to
2105 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002106 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2107 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002108 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2109 // Neither conversion sequence converts to a void pointer; compare
2110 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002111 if (ImplicitConversionSequence::CompareKind DerivedCK
2112 = CompareDerivedToBaseConversions(SCS1, SCS2))
2113 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002114 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2115 // Both conversion sequences are conversions to void
2116 // pointers. Compare the source types to determine if there's an
2117 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002118 QualType FromType1 = SCS1.getFromType();
2119 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002120
2121 // Adjust the types we're converting from via the array-to-pointer
2122 // conversion, if we need to.
2123 if (SCS1.First == ICK_Array_To_Pointer)
2124 FromType1 = Context.getArrayDecayedType(FromType1);
2125 if (SCS2.First == ICK_Array_To_Pointer)
2126 FromType2 = Context.getArrayDecayedType(FromType2);
2127
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002128 QualType FromPointee1
2129 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2130 QualType FromPointee2
2131 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002132
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002133 if (IsDerivedFrom(FromPointee2, FromPointee1))
2134 return ImplicitConversionSequence::Better;
2135 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2136 return ImplicitConversionSequence::Worse;
2137
2138 // Objective-C++: If one interface is more specific than the
2139 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002140 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2141 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002142 if (FromIface1 && FromIface1) {
2143 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2144 return ImplicitConversionSequence::Better;
2145 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2146 return ImplicitConversionSequence::Worse;
2147 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002148 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002149
2150 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2151 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002152 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002153 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002154 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002155
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002156 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002157 // C++0x [over.ics.rank]p3b4:
2158 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2159 // implicit object parameter of a non-static member function declared
2160 // without a ref-qualifier, and S1 binds an rvalue reference to an
2161 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002162 // FIXME: We don't know if we're dealing with the implicit object parameter,
2163 // or if the member function in this case has a ref qualifier.
2164 // (Of course, we don't have ref qualifiers yet.)
2165 if (SCS1.RRefBinding != SCS2.RRefBinding)
2166 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2167 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002168
2169 // C++ [over.ics.rank]p3b4:
2170 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2171 // which the references refer are the same type except for
2172 // top-level cv-qualifiers, and the type to which the reference
2173 // initialized by S2 refers is more cv-qualified than the type
2174 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002175 QualType T1 = SCS1.getToType(2);
2176 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002177 T1 = Context.getCanonicalType(T1);
2178 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002179 Qualifiers T1Quals, T2Quals;
2180 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2181 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2182 if (UnqualT1 == UnqualT2) {
2183 // If the type is an array type, promote the element qualifiers to the type
2184 // for comparison.
2185 if (isa<ArrayType>(T1) && T1Quals)
2186 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2187 if (isa<ArrayType>(T2) && T2Quals)
2188 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002189 if (T2.isMoreQualifiedThan(T1))
2190 return ImplicitConversionSequence::Better;
2191 else if (T1.isMoreQualifiedThan(T2))
2192 return ImplicitConversionSequence::Worse;
2193 }
2194 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002195
2196 return ImplicitConversionSequence::Indistinguishable;
2197}
2198
2199/// CompareQualificationConversions - Compares two standard conversion
2200/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002201/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2202ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002203Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002204 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002205 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002206 // -- S1 and S2 differ only in their qualification conversion and
2207 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2208 // cv-qualification signature of type T1 is a proper subset of
2209 // the cv-qualification signature of type T2, and S1 is not the
2210 // deprecated string literal array-to-pointer conversion (4.2).
2211 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2212 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2213 return ImplicitConversionSequence::Indistinguishable;
2214
2215 // FIXME: the example in the standard doesn't use a qualification
2216 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002217 QualType T1 = SCS1.getToType(2);
2218 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002219 T1 = Context.getCanonicalType(T1);
2220 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002221 Qualifiers T1Quals, T2Quals;
2222 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2223 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002224
2225 // If the types are the same, we won't learn anything by unwrapped
2226 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002227 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002228 return ImplicitConversionSequence::Indistinguishable;
2229
Chandler Carruth607f38e2009-12-29 07:16:59 +00002230 // If the type is an array type, promote the element qualifiers to the type
2231 // for comparison.
2232 if (isa<ArrayType>(T1) && T1Quals)
2233 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2234 if (isa<ArrayType>(T2) && T2Quals)
2235 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2236
Mike Stump11289f42009-09-09 15:08:12 +00002237 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002238 = ImplicitConversionSequence::Indistinguishable;
2239 while (UnwrapSimilarPointerTypes(T1, T2)) {
2240 // Within each iteration of the loop, we check the qualifiers to
2241 // determine if this still looks like a qualification
2242 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002243 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002244 // until there are no more pointers or pointers-to-members left
2245 // to unwrap. This essentially mimics what
2246 // IsQualificationConversion does, but here we're checking for a
2247 // strict subset of qualifiers.
2248 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2249 // The qualifiers are the same, so this doesn't tell us anything
2250 // about how the sequences rank.
2251 ;
2252 else if (T2.isMoreQualifiedThan(T1)) {
2253 // T1 has fewer qualifiers, so it could be the better sequence.
2254 if (Result == ImplicitConversionSequence::Worse)
2255 // Neither has qualifiers that are a subset of the other's
2256 // qualifiers.
2257 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002258
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002259 Result = ImplicitConversionSequence::Better;
2260 } else if (T1.isMoreQualifiedThan(T2)) {
2261 // T2 has fewer qualifiers, so it could be the better sequence.
2262 if (Result == ImplicitConversionSequence::Better)
2263 // Neither has qualifiers that are a subset of the other's
2264 // qualifiers.
2265 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002266
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002267 Result = ImplicitConversionSequence::Worse;
2268 } else {
2269 // Qualifiers are disjoint.
2270 return ImplicitConversionSequence::Indistinguishable;
2271 }
2272
2273 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002274 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002275 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002276 }
2277
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002278 // Check that the winning standard conversion sequence isn't using
2279 // the deprecated string literal array to pointer conversion.
2280 switch (Result) {
2281 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002282 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002283 Result = ImplicitConversionSequence::Indistinguishable;
2284 break;
2285
2286 case ImplicitConversionSequence::Indistinguishable:
2287 break;
2288
2289 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002290 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002291 Result = ImplicitConversionSequence::Indistinguishable;
2292 break;
2293 }
2294
2295 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002296}
2297
Douglas Gregor5c407d92008-10-23 00:40:37 +00002298/// CompareDerivedToBaseConversions - Compares two standard conversion
2299/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002300/// various kinds of derived-to-base conversions (C++
2301/// [over.ics.rank]p4b3). As part of these checks, we also look at
2302/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002303ImplicitConversionSequence::CompareKind
2304Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2305 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002306 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002307 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002308 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002309 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002310
2311 // Adjust the types we're converting from via the array-to-pointer
2312 // conversion, if we need to.
2313 if (SCS1.First == ICK_Array_To_Pointer)
2314 FromType1 = Context.getArrayDecayedType(FromType1);
2315 if (SCS2.First == ICK_Array_To_Pointer)
2316 FromType2 = Context.getArrayDecayedType(FromType2);
2317
2318 // Canonicalize all of the types.
2319 FromType1 = Context.getCanonicalType(FromType1);
2320 ToType1 = Context.getCanonicalType(ToType1);
2321 FromType2 = Context.getCanonicalType(FromType2);
2322 ToType2 = Context.getCanonicalType(ToType2);
2323
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002324 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002325 //
2326 // If class B is derived directly or indirectly from class A and
2327 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002328 //
2329 // For Objective-C, we let A, B, and C also be Objective-C
2330 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002331
2332 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002333 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002334 SCS2.Second == ICK_Pointer_Conversion &&
2335 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2336 FromType1->isPointerType() && FromType2->isPointerType() &&
2337 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002338 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002339 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002340 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002341 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002342 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002343 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002344 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002345 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002346
John McCall8b07ec22010-05-15 11:32:37 +00002347 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2348 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2349 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2350 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002351
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002352 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002353 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2354 if (IsDerivedFrom(ToPointee1, ToPointee2))
2355 return ImplicitConversionSequence::Better;
2356 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2357 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002358
2359 if (ToIface1 && ToIface2) {
2360 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2361 return ImplicitConversionSequence::Better;
2362 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2363 return ImplicitConversionSequence::Worse;
2364 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002365 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002366
2367 // -- conversion of B* to A* is better than conversion of C* to A*,
2368 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2369 if (IsDerivedFrom(FromPointee2, FromPointee1))
2370 return ImplicitConversionSequence::Better;
2371 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2372 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002373
Douglas Gregor237f96c2008-11-26 23:31:11 +00002374 if (FromIface1 && FromIface2) {
2375 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2376 return ImplicitConversionSequence::Better;
2377 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2378 return ImplicitConversionSequence::Worse;
2379 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002380 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002381 }
2382
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002383 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002384 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2385 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2386 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2387 const MemberPointerType * FromMemPointer1 =
2388 FromType1->getAs<MemberPointerType>();
2389 const MemberPointerType * ToMemPointer1 =
2390 ToType1->getAs<MemberPointerType>();
2391 const MemberPointerType * FromMemPointer2 =
2392 FromType2->getAs<MemberPointerType>();
2393 const MemberPointerType * ToMemPointer2 =
2394 ToType2->getAs<MemberPointerType>();
2395 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2396 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2397 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2398 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2399 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2400 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2401 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2402 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002403 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002404 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2405 if (IsDerivedFrom(ToPointee1, ToPointee2))
2406 return ImplicitConversionSequence::Worse;
2407 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2408 return ImplicitConversionSequence::Better;
2409 }
2410 // conversion of B::* to C::* is better than conversion of A::* to C::*
2411 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2412 if (IsDerivedFrom(FromPointee1, FromPointee2))
2413 return ImplicitConversionSequence::Better;
2414 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2415 return ImplicitConversionSequence::Worse;
2416 }
2417 }
2418
Douglas Gregor5ab11652010-04-17 22:01:05 +00002419 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002420 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002421 // -- binding of an expression of type C to a reference of type
2422 // B& is better than binding an expression of type C to a
2423 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002424 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2425 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002426 if (IsDerivedFrom(ToType1, ToType2))
2427 return ImplicitConversionSequence::Better;
2428 else if (IsDerivedFrom(ToType2, ToType1))
2429 return ImplicitConversionSequence::Worse;
2430 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002431
Douglas Gregor2fe98832008-11-03 19:09:14 +00002432 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002433 // -- binding of an expression of type B to a reference of type
2434 // A& is better than binding an expression of type C to a
2435 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002436 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2437 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002438 if (IsDerivedFrom(FromType2, FromType1))
2439 return ImplicitConversionSequence::Better;
2440 else if (IsDerivedFrom(FromType1, FromType2))
2441 return ImplicitConversionSequence::Worse;
2442 }
2443 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002444
Douglas Gregor5c407d92008-10-23 00:40:37 +00002445 return ImplicitConversionSequence::Indistinguishable;
2446}
2447
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002448/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2449/// determine whether they are reference-related,
2450/// reference-compatible, reference-compatible with added
2451/// qualification, or incompatible, for use in C++ initialization by
2452/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2453/// type, and the first type (T1) is the pointee type of the reference
2454/// type being initialized.
2455Sema::ReferenceCompareResult
2456Sema::CompareReferenceRelationship(SourceLocation Loc,
2457 QualType OrigT1, QualType OrigT2,
2458 bool& DerivedToBase) {
2459 assert(!OrigT1->isReferenceType() &&
2460 "T1 must be the pointee type of the reference type");
2461 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2462
2463 QualType T1 = Context.getCanonicalType(OrigT1);
2464 QualType T2 = Context.getCanonicalType(OrigT2);
2465 Qualifiers T1Quals, T2Quals;
2466 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2467 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2468
2469 // C++ [dcl.init.ref]p4:
2470 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2471 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2472 // T1 is a base class of T2.
2473 if (UnqualT1 == UnqualT2)
2474 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002475 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002476 IsDerivedFrom(UnqualT2, UnqualT1))
2477 DerivedToBase = true;
2478 else
2479 return Ref_Incompatible;
2480
2481 // At this point, we know that T1 and T2 are reference-related (at
2482 // least).
2483
2484 // If the type is an array type, promote the element qualifiers to the type
2485 // for comparison.
2486 if (isa<ArrayType>(T1) && T1Quals)
2487 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2488 if (isa<ArrayType>(T2) && T2Quals)
2489 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2490
2491 // C++ [dcl.init.ref]p4:
2492 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2493 // reference-related to T2 and cv1 is the same cv-qualification
2494 // as, or greater cv-qualification than, cv2. For purposes of
2495 // overload resolution, cases for which cv1 is greater
2496 // cv-qualification than cv2 are identified as
2497 // reference-compatible with added qualification (see 13.3.3.2).
2498 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2499 return Ref_Compatible;
2500 else if (T1.isMoreQualifiedThan(T2))
2501 return Ref_Compatible_With_Added_Qualification;
2502 else
2503 return Ref_Related;
2504}
2505
2506/// \brief Compute an implicit conversion sequence for reference
2507/// initialization.
2508static ImplicitConversionSequence
2509TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2510 SourceLocation DeclLoc,
2511 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002512 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002513 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2514
2515 // Most paths end in a failed conversion.
2516 ImplicitConversionSequence ICS;
2517 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2518
2519 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2520 QualType T2 = Init->getType();
2521
2522 // If the initializer is the address of an overloaded function, try
2523 // to resolve the overloaded function. If all goes well, T2 is the
2524 // type of the resulting function.
2525 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2526 DeclAccessPair Found;
2527 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2528 false, Found))
2529 T2 = Fn->getType();
2530 }
2531
2532 // Compute some basic properties of the types and the initializer.
2533 bool isRValRef = DeclType->isRValueReferenceType();
2534 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002535 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002536 Sema::ReferenceCompareResult RefRelationship
2537 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2538
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002539
2540 // C++ [over.ics.ref]p3:
2541 // Except for an implicit object parameter, for which see 13.3.1,
2542 // a standard conversion sequence cannot be formed if it requires
2543 // binding an lvalue reference to non-const to an rvalue or
2544 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002545 //
2546 // FIXME: DPG doesn't trust this code. It seems far too early to
2547 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002548 if (isRValRef && InitLvalue == Expr::LV_Valid)
2549 return ICS;
2550
Douglas Gregor870f3742010-04-18 09:22:00 +00002551 // C++0x [dcl.init.ref]p16:
2552 // A reference to type "cv1 T1" is initialized by an expression
2553 // of type "cv2 T2" as follows:
2554
2555 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002556 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2557 // reference-compatible with "cv2 T2," or
2558 //
2559 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2560 if (InitLvalue == Expr::LV_Valid &&
2561 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2562 // C++ [over.ics.ref]p1:
2563 // When a parameter of reference type binds directly (8.5.3)
2564 // to an argument expression, the implicit conversion sequence
2565 // is the identity conversion, unless the argument expression
2566 // has a type that is a derived class of the parameter type,
2567 // in which case the implicit conversion sequence is a
2568 // derived-to-base Conversion (13.3.3.1).
2569 ICS.setStandard();
2570 ICS.Standard.First = ICK_Identity;
2571 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2572 ICS.Standard.Third = ICK_Identity;
2573 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2574 ICS.Standard.setToType(0, T2);
2575 ICS.Standard.setToType(1, T1);
2576 ICS.Standard.setToType(2, T1);
2577 ICS.Standard.ReferenceBinding = true;
2578 ICS.Standard.DirectBinding = true;
2579 ICS.Standard.RRefBinding = false;
2580 ICS.Standard.CopyConstructor = 0;
2581
2582 // Nothing more to do: the inaccessibility/ambiguity check for
2583 // derived-to-base conversions is suppressed when we're
2584 // computing the implicit conversion sequence (C++
2585 // [over.best.ics]p2).
2586 return ICS;
2587 }
2588
2589 // -- has a class type (i.e., T2 is a class type), where T1 is
2590 // not reference-related to T2, and can be implicitly
2591 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2592 // is reference-compatible with "cv3 T3" 92) (this
2593 // conversion is selected by enumerating the applicable
2594 // conversion functions (13.3.1.6) and choosing the best
2595 // one through overload resolution (13.3)),
2596 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2597 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2598 RefRelationship == Sema::Ref_Incompatible) {
2599 CXXRecordDecl *T2RecordDecl
2600 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2601
2602 OverloadCandidateSet CandidateSet(DeclLoc);
2603 const UnresolvedSetImpl *Conversions
2604 = T2RecordDecl->getVisibleConversionFunctions();
2605 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2606 E = Conversions->end(); I != E; ++I) {
2607 NamedDecl *D = *I;
2608 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2609 if (isa<UsingShadowDecl>(D))
2610 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2611
2612 FunctionTemplateDecl *ConvTemplate
2613 = dyn_cast<FunctionTemplateDecl>(D);
2614 CXXConversionDecl *Conv;
2615 if (ConvTemplate)
2616 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2617 else
2618 Conv = cast<CXXConversionDecl>(D);
2619
2620 // If the conversion function doesn't return a reference type,
2621 // it can't be considered for this conversion.
2622 if (Conv->getConversionType()->isLValueReferenceType() &&
2623 (AllowExplicit || !Conv->isExplicit())) {
2624 if (ConvTemplate)
2625 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2626 Init, DeclType, CandidateSet);
2627 else
2628 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2629 DeclType, CandidateSet);
2630 }
2631 }
2632
2633 OverloadCandidateSet::iterator Best;
2634 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2635 case OR_Success:
2636 // C++ [over.ics.ref]p1:
2637 //
2638 // [...] If the parameter binds directly to the result of
2639 // applying a conversion function to the argument
2640 // expression, the implicit conversion sequence is a
2641 // user-defined conversion sequence (13.3.3.1.2), with the
2642 // second standard conversion sequence either an identity
2643 // conversion or, if the conversion function returns an
2644 // entity of a type that is a derived class of the parameter
2645 // type, a derived-to-base Conversion.
2646 if (!Best->FinalConversion.DirectBinding)
2647 break;
2648
2649 ICS.setUserDefined();
2650 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2651 ICS.UserDefined.After = Best->FinalConversion;
2652 ICS.UserDefined.ConversionFunction = Best->Function;
2653 ICS.UserDefined.EllipsisConversion = false;
2654 assert(ICS.UserDefined.After.ReferenceBinding &&
2655 ICS.UserDefined.After.DirectBinding &&
2656 "Expected a direct reference binding!");
2657 return ICS;
2658
2659 case OR_Ambiguous:
2660 ICS.setAmbiguous();
2661 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2662 Cand != CandidateSet.end(); ++Cand)
2663 if (Cand->Viable)
2664 ICS.Ambiguous.addConversion(Cand->Function);
2665 return ICS;
2666
2667 case OR_No_Viable_Function:
2668 case OR_Deleted:
2669 // There was no suitable conversion, or we found a deleted
2670 // conversion; continue with other checks.
2671 break;
2672 }
2673 }
2674
2675 // -- Otherwise, the reference shall be to a non-volatile const
2676 // type (i.e., cv1 shall be const), or the reference shall be an
2677 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002678 //
2679 // We actually handle one oddity of C++ [over.ics.ref] at this
2680 // point, which is that, due to p2 (which short-circuits reference
2681 // binding by only attempting a simple conversion for non-direct
2682 // bindings) and p3's strange wording, we allow a const volatile
2683 // reference to bind to an rvalue. Hence the check for the presence
2684 // of "const" rather than checking for "const" being the only
2685 // qualifier.
2686 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002687 return ICS;
2688
Douglas Gregorf93df192010-04-18 08:46:23 +00002689 // -- if T2 is a class type and
2690 // -- the initializer expression is an rvalue and "cv1 T1"
2691 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002692 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002693 // -- T1 is not reference-related to T2 and the initializer
2694 // expression can be implicitly converted to an rvalue
2695 // of type "cv3 T3" (this conversion is selected by
2696 // enumerating the applicable conversion functions
2697 // (13.3.1.6) and choosing the best one through overload
2698 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002699 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002700 // then the reference is bound to the initializer
2701 // expression rvalue in the first case and to the object
2702 // that is the result of the conversion in the second case
2703 // (or, in either case, to the appropriate base class
2704 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002705 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002706 // We're only checking the first case here, which is a direct
2707 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002708 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2709 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2710 ICS.setStandard();
2711 ICS.Standard.First = ICK_Identity;
2712 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2713 ICS.Standard.Third = ICK_Identity;
2714 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2715 ICS.Standard.setToType(0, T2);
2716 ICS.Standard.setToType(1, T1);
2717 ICS.Standard.setToType(2, T1);
2718 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002719 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002720 ICS.Standard.RRefBinding = isRValRef;
2721 ICS.Standard.CopyConstructor = 0;
2722 return ICS;
2723 }
2724
2725 // -- Otherwise, a temporary of type "cv1 T1" is created and
2726 // initialized from the initializer expression using the
2727 // rules for a non-reference copy initialization (8.5). The
2728 // reference is then bound to the temporary. If T1 is
2729 // reference-related to T2, cv1 must be the same
2730 // cv-qualification as, or greater cv-qualification than,
2731 // cv2; otherwise, the program is ill-formed.
2732 if (RefRelationship == Sema::Ref_Related) {
2733 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2734 // we would be reference-compatible or reference-compatible with
2735 // added qualification. But that wasn't the case, so the reference
2736 // initialization fails.
2737 return ICS;
2738 }
2739
2740 // If at least one of the types is a class type, the types are not
2741 // related, and we aren't allowed any user conversions, the
2742 // reference binding fails. This case is important for breaking
2743 // recursion, since TryImplicitConversion below will attempt to
2744 // create a temporary through the use of a copy constructor.
2745 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2746 (T1->isRecordType() || T2->isRecordType()))
2747 return ICS;
2748
2749 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002750 // When a parameter of reference type is not bound directly to
2751 // an argument expression, the conversion sequence is the one
2752 // required to convert the argument expression to the
2753 // underlying type of the reference according to
2754 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2755 // to copy-initializing a temporary of the underlying type with
2756 // the argument expression. Any difference in top-level
2757 // cv-qualification is subsumed by the initialization itself
2758 // and does not constitute a conversion.
2759 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2760 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002761 /*InOverloadResolution=*/false);
2762
2763 // Of course, that's still a reference binding.
2764 if (ICS.isStandard()) {
2765 ICS.Standard.ReferenceBinding = true;
2766 ICS.Standard.RRefBinding = isRValRef;
2767 } else if (ICS.isUserDefined()) {
2768 ICS.UserDefined.After.ReferenceBinding = true;
2769 ICS.UserDefined.After.RRefBinding = isRValRef;
2770 }
2771 return ICS;
2772}
2773
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002774/// TryCopyInitialization - Try to copy-initialize a value of type
2775/// ToType from the expression From. Return the implicit conversion
2776/// sequence required to pass this argument, which may be a bad
2777/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002778/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002779/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002780static ImplicitConversionSequence
2781TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002782 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002783 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002784 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002785 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002786 /*FIXME:*/From->getLocStart(),
2787 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002788 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002789
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002790 return S.TryImplicitConversion(From, ToType,
2791 SuppressUserConversions,
2792 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002793 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002794}
2795
Douglas Gregor436424c2008-11-18 23:14:02 +00002796/// TryObjectArgumentInitialization - Try to initialize the object
2797/// parameter of the given member function (@c Method) from the
2798/// expression @p From.
2799ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002800Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002801 CXXMethodDecl *Method,
2802 CXXRecordDecl *ActingContext) {
2803 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002804 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2805 // const volatile object.
2806 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2807 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2808 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002809
2810 // Set up the conversion sequence as a "bad" conversion, to allow us
2811 // to exit early.
2812 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002813
2814 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002815 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002816 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002817 FromType = PT->getPointeeType();
2818
2819 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002820
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002821 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002822 // where X is the class of which the function is a member
2823 // (C++ [over.match.funcs]p4). However, when finding an implicit
2824 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002825 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002826 // (C++ [over.match.funcs]p5). We perform a simplified version of
2827 // reference binding here, that allows class rvalues to bind to
2828 // non-constant references.
2829
2830 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2831 // with the implicit object parameter (C++ [over.match.funcs]p5).
2832 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002833 if (ImplicitParamType.getCVRQualifiers()
2834 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002835 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002836 ICS.setBad(BadConversionSequence::bad_qualifiers,
2837 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002838 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002839 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002840
2841 // Check that we have either the same type or a derived type. It
2842 // affects the conversion rank.
2843 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002844 ImplicitConversionKind SecondKind;
2845 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2846 SecondKind = ICK_Identity;
2847 } else if (IsDerivedFrom(FromType, ClassType))
2848 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002849 else {
John McCall65eb8792010-02-25 01:37:24 +00002850 ICS.setBad(BadConversionSequence::unrelated_class,
2851 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002852 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002853 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002854
2855 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002856 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002857 ICS.Standard.setAsIdentityConversion();
2858 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002859 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002860 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002861 ICS.Standard.ReferenceBinding = true;
2862 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002863 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002864 return ICS;
2865}
2866
2867/// PerformObjectArgumentInitialization - Perform initialization of
2868/// the implicit object parameter for the given Method with the given
2869/// expression.
2870bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002871Sema::PerformObjectArgumentInitialization(Expr *&From,
2872 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002873 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002874 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002875 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002876 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002877 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002878
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002879 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002880 FromRecordType = PT->getPointeeType();
2881 DestType = Method->getThisType(Context);
2882 } else {
2883 FromRecordType = From->getType();
2884 DestType = ImplicitParamRecordType;
2885 }
2886
John McCall6e9f8f62009-12-03 04:06:58 +00002887 // Note that we always use the true parent context when performing
2888 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002889 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002890 = TryObjectArgumentInitialization(From->getType(), Method,
2891 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002892 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002893 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002894 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002895 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002896
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002897 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002898 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002899
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002900 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002901 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2902 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002903 return false;
2904}
2905
Douglas Gregor5fb53972009-01-14 15:45:31 +00002906/// TryContextuallyConvertToBool - Attempt to contextually convert the
2907/// expression From to bool (C++0x [conv]p3).
2908ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002909 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00002910 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002911 // FIXME: Are these flags correct?
2912 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002913 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002914 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002915}
2916
2917/// PerformContextuallyConvertToBool - Perform a contextual conversion
2918/// of the expression From to bool (C++0x [conv]p3).
2919bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2920 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002921 if (!ICS.isBad())
2922 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002923
Fariborz Jahanian76197412009-11-18 18:26:29 +00002924 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002925 return Diag(From->getSourceRange().getBegin(),
2926 diag::err_typecheck_bool_condition)
2927 << From->getType() << From->getSourceRange();
2928 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002929}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00002930
2931/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
2932/// expression From to 'id'.
2933ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00002934 QualType Ty = Context.getObjCIdType();
2935 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00002936 // FIXME: Are these flags correct?
2937 /*SuppressUserConversions=*/false,
2938 /*AllowExplicit=*/true,
2939 /*InOverloadResolution=*/false);
2940}
2941
2942/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
2943/// of the expression From to 'id'.
2944bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00002945 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00002946 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
2947 if (!ICS.isBad())
2948 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
2949 return true;
2950}
Douglas Gregor5fb53972009-01-14 15:45:31 +00002951
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002952/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002953/// candidate functions, using the given function call arguments. If
2954/// @p SuppressUserConversions, then don't allow user-defined
2955/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002956///
2957/// \para PartialOverloading true if we are performing "partial" overloading
2958/// based on an incomplete set of function arguments. This feature is used by
2959/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002960void
2961Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002962 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002963 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002964 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002965 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002966 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002967 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002968 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002969 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002970 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002971 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002972
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002973 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002974 if (!isa<CXXConstructorDecl>(Method)) {
2975 // If we get here, it's because we're calling a member function
2976 // that is named without a member access expression (e.g.,
2977 // "this->f") that was either written explicitly or created
2978 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002979 // function, e.g., X::f(). We use an empty type for the implied
2980 // object argument (C++ [over.call.func]p3), and the acting context
2981 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002982 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002983 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002984 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002985 return;
2986 }
2987 // We treat a constructor like a non-member function, since its object
2988 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002989 }
2990
Douglas Gregorff7028a2009-11-13 23:59:09 +00002991 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002992 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002993
Douglas Gregor27381f32009-11-23 12:27:39 +00002994 // Overload resolution is always an unevaluated context.
2995 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2996
Douglas Gregorffe14e32009-11-14 01:20:54 +00002997 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2998 // C++ [class.copy]p3:
2999 // A member function template is never instantiated to perform the copy
3000 // of a class object to an object of its class type.
3001 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3002 if (NumArgs == 1 &&
3003 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003004 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3005 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003006 return;
3007 }
3008
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003009 // Add this candidate
3010 CandidateSet.push_back(OverloadCandidate());
3011 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003012 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003013 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003014 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003015 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003016 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003017
3018 unsigned NumArgsInProto = Proto->getNumArgs();
3019
3020 // (C++ 13.3.2p2): A candidate function having fewer than m
3021 // parameters is viable only if it has an ellipsis in its parameter
3022 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003023 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3024 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003025 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003026 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003027 return;
3028 }
3029
3030 // (C++ 13.3.2p2): A candidate function having more than m parameters
3031 // is viable only if the (m+1)st parameter has a default argument
3032 // (8.3.6). For the purposes of overload resolution, the
3033 // parameter list is truncated on the right, so that there are
3034 // exactly m parameters.
3035 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003036 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003037 // Not enough arguments.
3038 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003039 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003040 return;
3041 }
3042
3043 // Determine the implicit conversion sequences for each of the
3044 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003045 Candidate.Conversions.resize(NumArgs);
3046 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3047 if (ArgIdx < NumArgsInProto) {
3048 // (C++ 13.3.2p3): for F to be a viable function, there shall
3049 // exist for each argument an implicit conversion sequence
3050 // (13.3.3.1) that converts that argument to the corresponding
3051 // parameter of F.
3052 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003053 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003054 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003055 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003056 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003057 if (Candidate.Conversions[ArgIdx].isBad()) {
3058 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003059 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003060 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003061 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003062 } else {
3063 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3064 // argument for which there is no corresponding parameter is
3065 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003066 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003067 }
3068 }
3069}
3070
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003071/// \brief Add all of the function declarations in the given function set to
3072/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003073void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003074 Expr **Args, unsigned NumArgs,
3075 OverloadCandidateSet& CandidateSet,
3076 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003077 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003078 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3079 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003080 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003081 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003082 cast<CXXMethodDecl>(FD)->getParent(),
3083 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003084 CandidateSet, SuppressUserConversions);
3085 else
John McCalla0296f72010-03-19 07:35:19 +00003086 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003087 SuppressUserConversions);
3088 } else {
John McCalla0296f72010-03-19 07:35:19 +00003089 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003090 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3091 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003092 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003093 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003094 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003095 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003096 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003097 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003098 else
John McCalla0296f72010-03-19 07:35:19 +00003099 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003100 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003101 Args, NumArgs, CandidateSet,
3102 SuppressUserConversions);
3103 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003104 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003105}
3106
John McCallf0f1cf02009-11-17 07:50:12 +00003107/// AddMethodCandidate - Adds a named decl (which is some kind of
3108/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003109void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003110 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003111 Expr **Args, unsigned NumArgs,
3112 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003113 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003114 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003115 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003116
3117 if (isa<UsingShadowDecl>(Decl))
3118 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3119
3120 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3121 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3122 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003123 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3124 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003125 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003126 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003127 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003128 } else {
John McCalla0296f72010-03-19 07:35:19 +00003129 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003130 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003131 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003132 }
3133}
3134
Douglas Gregor436424c2008-11-18 23:14:02 +00003135/// AddMethodCandidate - Adds the given C++ member function to the set
3136/// of candidate functions, using the given function call arguments
3137/// and the object argument (@c Object). For example, in a call
3138/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3139/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3140/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003141/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003142void
John McCalla0296f72010-03-19 07:35:19 +00003143Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003144 CXXRecordDecl *ActingContext, QualType ObjectType,
3145 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003146 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003147 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003148 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003149 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003150 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003151 assert(!isa<CXXConstructorDecl>(Method) &&
3152 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003153
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003154 if (!CandidateSet.isNewCandidate(Method))
3155 return;
3156
Douglas Gregor27381f32009-11-23 12:27:39 +00003157 // Overload resolution is always an unevaluated context.
3158 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3159
Douglas Gregor436424c2008-11-18 23:14:02 +00003160 // Add this candidate
3161 CandidateSet.push_back(OverloadCandidate());
3162 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003163 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003164 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003165 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003166 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003167
3168 unsigned NumArgsInProto = Proto->getNumArgs();
3169
3170 // (C++ 13.3.2p2): A candidate function having fewer than m
3171 // parameters is viable only if it has an ellipsis in its parameter
3172 // list (8.3.5).
3173 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3174 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003175 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003176 return;
3177 }
3178
3179 // (C++ 13.3.2p2): A candidate function having more than m parameters
3180 // is viable only if the (m+1)st parameter has a default argument
3181 // (8.3.6). For the purposes of overload resolution, the
3182 // parameter list is truncated on the right, so that there are
3183 // exactly m parameters.
3184 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3185 if (NumArgs < MinRequiredArgs) {
3186 // Not enough arguments.
3187 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003188 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003189 return;
3190 }
3191
3192 Candidate.Viable = true;
3193 Candidate.Conversions.resize(NumArgs + 1);
3194
John McCall6e9f8f62009-12-03 04:06:58 +00003195 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003196 // The implicit object argument is ignored.
3197 Candidate.IgnoreObjectArgument = true;
3198 else {
3199 // Determine the implicit conversion sequence for the object
3200 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003201 Candidate.Conversions[0]
3202 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003203 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003204 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003205 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003206 return;
3207 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003208 }
3209
3210 // Determine the implicit conversion sequences for each of the
3211 // arguments.
3212 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3213 if (ArgIdx < NumArgsInProto) {
3214 // (C++ 13.3.2p3): for F to be a viable function, there shall
3215 // exist for each argument an implicit conversion sequence
3216 // (13.3.3.1) that converts that argument to the corresponding
3217 // parameter of F.
3218 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003219 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003220 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003221 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003222 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003223 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003224 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003225 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003226 break;
3227 }
3228 } else {
3229 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3230 // argument for which there is no corresponding parameter is
3231 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003232 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003233 }
3234 }
3235}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003236
Douglas Gregor97628d62009-08-21 00:16:32 +00003237/// \brief Add a C++ member function template as a candidate to the candidate
3238/// set, using template argument deduction to produce an appropriate member
3239/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003240void
Douglas Gregor97628d62009-08-21 00:16:32 +00003241Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003242 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003243 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003244 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003245 QualType ObjectType,
3246 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003247 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003248 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003249 if (!CandidateSet.isNewCandidate(MethodTmpl))
3250 return;
3251
Douglas Gregor97628d62009-08-21 00:16:32 +00003252 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003253 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003254 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003255 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003256 // candidate functions in the usual way.113) A given name can refer to one
3257 // or more function templates and also to a set of overloaded non-template
3258 // functions. In such a case, the candidate functions generated from each
3259 // function template are combined with the set of non-template candidate
3260 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003261 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003262 FunctionDecl *Specialization = 0;
3263 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003264 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003265 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003266 CandidateSet.push_back(OverloadCandidate());
3267 OverloadCandidate &Candidate = CandidateSet.back();
3268 Candidate.FoundDecl = FoundDecl;
3269 Candidate.Function = MethodTmpl->getTemplatedDecl();
3270 Candidate.Viable = false;
3271 Candidate.FailureKind = ovl_fail_bad_deduction;
3272 Candidate.IsSurrogate = false;
3273 Candidate.IgnoreObjectArgument = false;
3274 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3275 Info);
3276 return;
3277 }
Mike Stump11289f42009-09-09 15:08:12 +00003278
Douglas Gregor97628d62009-08-21 00:16:32 +00003279 // Add the function template specialization produced by template argument
3280 // deduction as a candidate.
3281 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003282 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003283 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003284 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003285 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003286 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003287}
3288
Douglas Gregor05155d82009-08-21 23:19:43 +00003289/// \brief Add a C++ function template specialization as a candidate
3290/// in the candidate set, using template argument deduction to produce
3291/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003292void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003293Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003294 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003295 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003296 Expr **Args, unsigned NumArgs,
3297 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003298 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003299 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3300 return;
3301
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003302 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003303 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003304 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003305 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003306 // candidate functions in the usual way.113) A given name can refer to one
3307 // or more function templates and also to a set of overloaded non-template
3308 // functions. In such a case, the candidate functions generated from each
3309 // function template are combined with the set of non-template candidate
3310 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003311 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003312 FunctionDecl *Specialization = 0;
3313 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003314 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003315 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003316 CandidateSet.push_back(OverloadCandidate());
3317 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003318 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003319 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3320 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003321 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003322 Candidate.IsSurrogate = false;
3323 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003324 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3325 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003326 return;
3327 }
Mike Stump11289f42009-09-09 15:08:12 +00003328
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003329 // Add the function template specialization produced by template argument
3330 // deduction as a candidate.
3331 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003332 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003333 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003334}
Mike Stump11289f42009-09-09 15:08:12 +00003335
Douglas Gregora1f013e2008-11-07 22:36:19 +00003336/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003337/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003338/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003339/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003340/// (which may or may not be the same type as the type that the
3341/// conversion function produces).
3342void
3343Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003344 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003345 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003346 Expr *From, QualType ToType,
3347 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003348 assert(!Conversion->getDescribedFunctionTemplate() &&
3349 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003350 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003351 if (!CandidateSet.isNewCandidate(Conversion))
3352 return;
3353
Douglas Gregor27381f32009-11-23 12:27:39 +00003354 // Overload resolution is always an unevaluated context.
3355 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3356
Douglas Gregora1f013e2008-11-07 22:36:19 +00003357 // Add this candidate
3358 CandidateSet.push_back(OverloadCandidate());
3359 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003360 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003361 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003362 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003363 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003364 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003365 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003366 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003367
Douglas Gregor436424c2008-11-18 23:14:02 +00003368 // Determine the implicit conversion sequence for the implicit
3369 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003370 Candidate.Viable = true;
3371 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003372 Candidate.Conversions[0]
3373 = TryObjectArgumentInitialization(From->getType(), Conversion,
3374 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003375 // Conversion functions to a different type in the base class is visible in
3376 // the derived class. So, a derived to base conversion should not participate
3377 // in overload resolution.
3378 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3379 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003380 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003381 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003382 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003383 return;
3384 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003385
3386 // We won't go through a user-define type conversion function to convert a
3387 // derived to base as such conversions are given Conversion Rank. They only
3388 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3389 QualType FromCanon
3390 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3391 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3392 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3393 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003394 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003395 return;
3396 }
3397
Douglas Gregora1f013e2008-11-07 22:36:19 +00003398 // To determine what the conversion from the result of calling the
3399 // conversion function to the type we're eventually trying to
3400 // convert to (ToType), we need to synthesize a call to the
3401 // conversion function and attempt copy initialization from it. This
3402 // makes sure that we get the right semantics with respect to
3403 // lvalues/rvalues and the type. Fortunately, we can allocate this
3404 // call on the stack and we don't need its arguments to be
3405 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003406 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003407 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003408 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003409 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003410 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003411
3412 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003413 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3414 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003415 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003416 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003417 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003418 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003419 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003420 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003421 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003422
John McCall0d1da222010-01-12 00:44:57 +00003423 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003424 case ImplicitConversionSequence::StandardConversion:
3425 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003426
3427 // C++ [over.ics.user]p3:
3428 // If the user-defined conversion is specified by a specialization of a
3429 // conversion function template, the second standard conversion sequence
3430 // shall have exact match rank.
3431 if (Conversion->getPrimaryTemplate() &&
3432 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3433 Candidate.Viable = false;
3434 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3435 }
3436
Douglas Gregora1f013e2008-11-07 22:36:19 +00003437 break;
3438
3439 case ImplicitConversionSequence::BadConversion:
3440 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003441 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003442 break;
3443
3444 default:
Mike Stump11289f42009-09-09 15:08:12 +00003445 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003446 "Can only end up with a standard conversion sequence or failure");
3447 }
3448}
3449
Douglas Gregor05155d82009-08-21 23:19:43 +00003450/// \brief Adds a conversion function template specialization
3451/// candidate to the overload set, using template argument deduction
3452/// to deduce the template arguments of the conversion function
3453/// template from the type that we are converting to (C++
3454/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003455void
Douglas Gregor05155d82009-08-21 23:19:43 +00003456Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003457 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003458 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003459 Expr *From, QualType ToType,
3460 OverloadCandidateSet &CandidateSet) {
3461 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3462 "Only conversion function templates permitted here");
3463
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003464 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3465 return;
3466
John McCallbc077cf2010-02-08 23:07:23 +00003467 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003468 CXXConversionDecl *Specialization = 0;
3469 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003470 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003471 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003472 CandidateSet.push_back(OverloadCandidate());
3473 OverloadCandidate &Candidate = CandidateSet.back();
3474 Candidate.FoundDecl = FoundDecl;
3475 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3476 Candidate.Viable = false;
3477 Candidate.FailureKind = ovl_fail_bad_deduction;
3478 Candidate.IsSurrogate = false;
3479 Candidate.IgnoreObjectArgument = false;
3480 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3481 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003482 return;
3483 }
Mike Stump11289f42009-09-09 15:08:12 +00003484
Douglas Gregor05155d82009-08-21 23:19:43 +00003485 // Add the conversion function template specialization produced by
3486 // template argument deduction as a candidate.
3487 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003488 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003489 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003490}
3491
Douglas Gregorab7897a2008-11-19 22:57:39 +00003492/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3493/// converts the given @c Object to a function pointer via the
3494/// conversion function @c Conversion, and then attempts to call it
3495/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3496/// the type of function that we'll eventually be calling.
3497void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003498 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003499 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003500 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003501 QualType ObjectType,
3502 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003503 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003504 if (!CandidateSet.isNewCandidate(Conversion))
3505 return;
3506
Douglas Gregor27381f32009-11-23 12:27:39 +00003507 // Overload resolution is always an unevaluated context.
3508 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3509
Douglas Gregorab7897a2008-11-19 22:57:39 +00003510 CandidateSet.push_back(OverloadCandidate());
3511 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003512 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003513 Candidate.Function = 0;
3514 Candidate.Surrogate = Conversion;
3515 Candidate.Viable = true;
3516 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003517 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003518 Candidate.Conversions.resize(NumArgs + 1);
3519
3520 // Determine the implicit conversion sequence for the implicit
3521 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003522 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003523 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003524 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003525 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003526 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003527 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003528 return;
3529 }
3530
3531 // The first conversion is actually a user-defined conversion whose
3532 // first conversion is ObjectInit's standard conversion (which is
3533 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003534 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003535 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003536 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003537 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003538 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003539 = Candidate.Conversions[0].UserDefined.Before;
3540 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3541
Mike Stump11289f42009-09-09 15:08:12 +00003542 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003543 unsigned NumArgsInProto = Proto->getNumArgs();
3544
3545 // (C++ 13.3.2p2): A candidate function having fewer than m
3546 // parameters is viable only if it has an ellipsis in its parameter
3547 // list (8.3.5).
3548 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3549 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003550 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003551 return;
3552 }
3553
3554 // Function types don't have any default arguments, so just check if
3555 // we have enough arguments.
3556 if (NumArgs < NumArgsInProto) {
3557 // Not enough arguments.
3558 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003559 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003560 return;
3561 }
3562
3563 // Determine the implicit conversion sequences for each of the
3564 // arguments.
3565 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3566 if (ArgIdx < NumArgsInProto) {
3567 // (C++ 13.3.2p3): for F to be a viable function, there shall
3568 // exist for each argument an implicit conversion sequence
3569 // (13.3.3.1) that converts that argument to the corresponding
3570 // parameter of F.
3571 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003572 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003573 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003574 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003575 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003576 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003577 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003578 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003579 break;
3580 }
3581 } else {
3582 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3583 // argument for which there is no corresponding parameter is
3584 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003585 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003586 }
3587 }
3588}
3589
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003590/// \brief Add overload candidates for overloaded operators that are
3591/// member functions.
3592///
3593/// Add the overloaded operator candidates that are member functions
3594/// for the operator Op that was used in an operator expression such
3595/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3596/// CandidateSet will store the added overload candidates. (C++
3597/// [over.match.oper]).
3598void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3599 SourceLocation OpLoc,
3600 Expr **Args, unsigned NumArgs,
3601 OverloadCandidateSet& CandidateSet,
3602 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003603 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3604
3605 // C++ [over.match.oper]p3:
3606 // For a unary operator @ with an operand of a type whose
3607 // cv-unqualified version is T1, and for a binary operator @ with
3608 // a left operand of a type whose cv-unqualified version is T1 and
3609 // a right operand of a type whose cv-unqualified version is T2,
3610 // three sets of candidate functions, designated member
3611 // candidates, non-member candidates and built-in candidates, are
3612 // constructed as follows:
3613 QualType T1 = Args[0]->getType();
3614 QualType T2;
3615 if (NumArgs > 1)
3616 T2 = Args[1]->getType();
3617
3618 // -- If T1 is a class type, the set of member candidates is the
3619 // result of the qualified lookup of T1::operator@
3620 // (13.3.1.1.1); otherwise, the set of member candidates is
3621 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003622 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003623 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003624 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003625 return;
Mike Stump11289f42009-09-09 15:08:12 +00003626
John McCall27b18f82009-11-17 02:14:36 +00003627 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3628 LookupQualifiedName(Operators, T1Rec->getDecl());
3629 Operators.suppressDiagnostics();
3630
Mike Stump11289f42009-09-09 15:08:12 +00003631 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003632 OperEnd = Operators.end();
3633 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003634 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003635 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003636 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003637 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003638 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003639}
3640
Douglas Gregora11693b2008-11-12 17:17:38 +00003641/// AddBuiltinCandidate - Add a candidate for a built-in
3642/// operator. ResultTy and ParamTys are the result and parameter types
3643/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003644/// arguments being passed to the candidate. IsAssignmentOperator
3645/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003646/// operator. NumContextualBoolArguments is the number of arguments
3647/// (at the beginning of the argument list) that will be contextually
3648/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003649void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003650 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003651 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003652 bool IsAssignmentOperator,
3653 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003654 // Overload resolution is always an unevaluated context.
3655 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3656
Douglas Gregora11693b2008-11-12 17:17:38 +00003657 // Add this candidate
3658 CandidateSet.push_back(OverloadCandidate());
3659 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003660 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003661 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003662 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003663 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003664 Candidate.BuiltinTypes.ResultTy = ResultTy;
3665 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3666 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3667
3668 // Determine the implicit conversion sequences for each of the
3669 // arguments.
3670 Candidate.Viable = true;
3671 Candidate.Conversions.resize(NumArgs);
3672 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003673 // C++ [over.match.oper]p4:
3674 // For the built-in assignment operators, conversions of the
3675 // left operand are restricted as follows:
3676 // -- no temporaries are introduced to hold the left operand, and
3677 // -- no user-defined conversions are applied to the left
3678 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003679 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003680 //
3681 // We block these conversions by turning off user-defined
3682 // conversions, since that is the only way that initialization of
3683 // a reference to a non-class type can occur from something that
3684 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003685 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003686 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003687 "Contextual conversion to bool requires bool type");
3688 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3689 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003690 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003691 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003692 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003693 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003694 }
John McCall0d1da222010-01-12 00:44:57 +00003695 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003696 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003697 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003698 break;
3699 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003700 }
3701}
3702
3703/// BuiltinCandidateTypeSet - A set of types that will be used for the
3704/// candidate operator functions for built-in operators (C++
3705/// [over.built]). The types are separated into pointer types and
3706/// enumeration types.
3707class BuiltinCandidateTypeSet {
3708 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003709 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003710
3711 /// PointerTypes - The set of pointer types that will be used in the
3712 /// built-in candidates.
3713 TypeSet PointerTypes;
3714
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003715 /// MemberPointerTypes - The set of member pointer types that will be
3716 /// used in the built-in candidates.
3717 TypeSet MemberPointerTypes;
3718
Douglas Gregora11693b2008-11-12 17:17:38 +00003719 /// EnumerationTypes - The set of enumeration types that will be
3720 /// used in the built-in candidates.
3721 TypeSet EnumerationTypes;
3722
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003723 /// Sema - The semantic analysis instance where we are building the
3724 /// candidate type set.
3725 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003726
Douglas Gregora11693b2008-11-12 17:17:38 +00003727 /// Context - The AST context in which we will build the type sets.
3728 ASTContext &Context;
3729
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003730 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3731 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003732 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003733
3734public:
3735 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003736 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003737
Mike Stump11289f42009-09-09 15:08:12 +00003738 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003739 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003740
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003741 void AddTypesConvertedFrom(QualType Ty,
3742 SourceLocation Loc,
3743 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003744 bool AllowExplicitConversions,
3745 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003746
3747 /// pointer_begin - First pointer type found;
3748 iterator pointer_begin() { return PointerTypes.begin(); }
3749
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003750 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003751 iterator pointer_end() { return PointerTypes.end(); }
3752
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003753 /// member_pointer_begin - First member pointer type found;
3754 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3755
3756 /// member_pointer_end - Past the last member pointer type found;
3757 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3758
Douglas Gregora11693b2008-11-12 17:17:38 +00003759 /// enumeration_begin - First enumeration type found;
3760 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3761
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003762 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003763 iterator enumeration_end() { return EnumerationTypes.end(); }
3764};
3765
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003766/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003767/// the set of pointer types along with any more-qualified variants of
3768/// that type. For example, if @p Ty is "int const *", this routine
3769/// will add "int const *", "int const volatile *", "int const
3770/// restrict *", and "int const volatile restrict *" to the set of
3771/// pointer types. Returns true if the add of @p Ty itself succeeded,
3772/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003773///
3774/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003775bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003776BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3777 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003778
Douglas Gregora11693b2008-11-12 17:17:38 +00003779 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003780 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003781 return false;
3782
John McCall8ccfcb52009-09-24 19:53:00 +00003783 const PointerType *PointerTy = Ty->getAs<PointerType>();
3784 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003785
John McCall8ccfcb52009-09-24 19:53:00 +00003786 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003787 // Don't add qualified variants of arrays. For one, they're not allowed
3788 // (the qualifier would sink to the element type), and for another, the
3789 // only overload situation where it matters is subscript or pointer +- int,
3790 // and those shouldn't have qualifier variants anyway.
3791 if (PointeeTy->isArrayType())
3792 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003793 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003794 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003795 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003796 bool hasVolatile = VisibleQuals.hasVolatile();
3797 bool hasRestrict = VisibleQuals.hasRestrict();
3798
John McCall8ccfcb52009-09-24 19:53:00 +00003799 // Iterate through all strict supersets of BaseCVR.
3800 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3801 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003802 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3803 // in the types.
3804 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3805 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003806 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3807 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003808 }
3809
3810 return true;
3811}
3812
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003813/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3814/// to the set of pointer types along with any more-qualified variants of
3815/// that type. For example, if @p Ty is "int const *", this routine
3816/// will add "int const *", "int const volatile *", "int const
3817/// restrict *", and "int const volatile restrict *" to the set of
3818/// pointer types. Returns true if the add of @p Ty itself succeeded,
3819/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003820///
3821/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003822bool
3823BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3824 QualType Ty) {
3825 // Insert this type.
3826 if (!MemberPointerTypes.insert(Ty))
3827 return false;
3828
John McCall8ccfcb52009-09-24 19:53:00 +00003829 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3830 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003831
John McCall8ccfcb52009-09-24 19:53:00 +00003832 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003833 // Don't add qualified variants of arrays. For one, they're not allowed
3834 // (the qualifier would sink to the element type), and for another, the
3835 // only overload situation where it matters is subscript or pointer +- int,
3836 // and those shouldn't have qualifier variants anyway.
3837 if (PointeeTy->isArrayType())
3838 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003839 const Type *ClassTy = PointerTy->getClass();
3840
3841 // Iterate through all strict supersets of the pointee type's CVR
3842 // qualifiers.
3843 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3844 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3845 if ((CVR | BaseCVR) != CVR) continue;
3846
3847 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3848 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003849 }
3850
3851 return true;
3852}
3853
Douglas Gregora11693b2008-11-12 17:17:38 +00003854/// AddTypesConvertedFrom - Add each of the types to which the type @p
3855/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003856/// primarily interested in pointer types and enumeration types. We also
3857/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003858/// AllowUserConversions is true if we should look at the conversion
3859/// functions of a class type, and AllowExplicitConversions if we
3860/// should also include the explicit conversion functions of a class
3861/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003862void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003863BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003864 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003865 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003866 bool AllowExplicitConversions,
3867 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003868 // Only deal with canonical types.
3869 Ty = Context.getCanonicalType(Ty);
3870
3871 // Look through reference types; they aren't part of the type of an
3872 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003873 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003874 Ty = RefTy->getPointeeType();
3875
3876 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003877 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003878
Sebastian Redl65ae2002009-11-05 16:36:20 +00003879 // If we're dealing with an array type, decay to the pointer.
3880 if (Ty->isArrayType())
3881 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3882
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003883 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003884 QualType PointeeTy = PointerTy->getPointeeType();
3885
3886 // Insert our type, and its more-qualified variants, into the set
3887 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003888 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003889 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003890 } else if (Ty->isMemberPointerType()) {
3891 // Member pointers are far easier, since the pointee can't be converted.
3892 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3893 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003894 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003895 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003896 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003897 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003898 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003899 // No conversion functions in incomplete types.
3900 return;
3901 }
Mike Stump11289f42009-09-09 15:08:12 +00003902
Douglas Gregora11693b2008-11-12 17:17:38 +00003903 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003904 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003905 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003906 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003907 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003908 NamedDecl *D = I.getDecl();
3909 if (isa<UsingShadowDecl>(D))
3910 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003911
Mike Stump11289f42009-09-09 15:08:12 +00003912 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003913 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003914 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003915 continue;
3916
John McCallda4458e2010-03-31 01:36:47 +00003917 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003918 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003919 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003920 VisibleQuals);
3921 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003922 }
3923 }
3924 }
3925}
3926
Douglas Gregor84605ae2009-08-24 13:43:27 +00003927/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3928/// the volatile- and non-volatile-qualified assignment operators for the
3929/// given type to the candidate set.
3930static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3931 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003932 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003933 unsigned NumArgs,
3934 OverloadCandidateSet &CandidateSet) {
3935 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003936
Douglas Gregor84605ae2009-08-24 13:43:27 +00003937 // T& operator=(T&, T)
3938 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3939 ParamTypes[1] = T;
3940 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3941 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003942
Douglas Gregor84605ae2009-08-24 13:43:27 +00003943 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3944 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003945 ParamTypes[0]
3946 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003947 ParamTypes[1] = T;
3948 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003949 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003950 }
3951}
Mike Stump11289f42009-09-09 15:08:12 +00003952
Sebastian Redl1054fae2009-10-25 17:03:50 +00003953/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3954/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003955static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3956 Qualifiers VRQuals;
3957 const RecordType *TyRec;
3958 if (const MemberPointerType *RHSMPType =
3959 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00003960 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003961 else
3962 TyRec = ArgExpr->getType()->getAs<RecordType>();
3963 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003964 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003965 VRQuals.addVolatile();
3966 VRQuals.addRestrict();
3967 return VRQuals;
3968 }
3969
3970 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003971 if (!ClassDecl->hasDefinition())
3972 return VRQuals;
3973
John McCallad371252010-01-20 00:46:10 +00003974 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003975 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003976
John McCallad371252010-01-20 00:46:10 +00003977 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003978 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003979 NamedDecl *D = I.getDecl();
3980 if (isa<UsingShadowDecl>(D))
3981 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3982 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003983 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3984 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3985 CanTy = ResTypeRef->getPointeeType();
3986 // Need to go down the pointer/mempointer chain and add qualifiers
3987 // as see them.
3988 bool done = false;
3989 while (!done) {
3990 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3991 CanTy = ResTypePtr->getPointeeType();
3992 else if (const MemberPointerType *ResTypeMPtr =
3993 CanTy->getAs<MemberPointerType>())
3994 CanTy = ResTypeMPtr->getPointeeType();
3995 else
3996 done = true;
3997 if (CanTy.isVolatileQualified())
3998 VRQuals.addVolatile();
3999 if (CanTy.isRestrictQualified())
4000 VRQuals.addRestrict();
4001 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4002 return VRQuals;
4003 }
4004 }
4005 }
4006 return VRQuals;
4007}
4008
Douglas Gregord08452f2008-11-19 15:42:04 +00004009/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4010/// operator overloads to the candidate set (C++ [over.built]), based
4011/// on the operator @p Op and the arguments given. For example, if the
4012/// operator is a binary '+', this routine might add "int
4013/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004014void
Mike Stump11289f42009-09-09 15:08:12 +00004015Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004016 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004017 Expr **Args, unsigned NumArgs,
4018 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004019 // The set of "promoted arithmetic types", which are the arithmetic
4020 // types are that preserved by promotion (C++ [over.built]p2). Note
4021 // that the first few of these types are the promoted integral
4022 // types; these types need to be first.
4023 // FIXME: What about complex?
4024 const unsigned FirstIntegralType = 0;
4025 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004026 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004027 LastPromotedIntegralType = 13;
4028 const unsigned FirstPromotedArithmeticType = 7,
4029 LastPromotedArithmeticType = 16;
4030 const unsigned NumArithmeticTypes = 16;
4031 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004032 Context.BoolTy, Context.CharTy, Context.WCharTy,
4033// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004034 Context.SignedCharTy, Context.ShortTy,
4035 Context.UnsignedCharTy, Context.UnsignedShortTy,
4036 Context.IntTy, Context.LongTy, Context.LongLongTy,
4037 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4038 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4039 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004040 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4041 "Invalid first promoted integral type");
4042 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4043 == Context.UnsignedLongLongTy &&
4044 "Invalid last promoted integral type");
4045 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4046 "Invalid first promoted arithmetic type");
4047 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4048 == Context.LongDoubleTy &&
4049 "Invalid last promoted arithmetic type");
4050
Douglas Gregora11693b2008-11-12 17:17:38 +00004051 // Find all of the types that the arguments can convert to, but only
4052 // if the operator we're looking at has built-in operator candidates
4053 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004054 Qualifiers VisibleTypeConversionsQuals;
4055 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004056 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4057 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4058
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004059 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00004060 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
4061 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00004062 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00004063 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00004064 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00004065 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004066 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00004067 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004068 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004069 true,
4070 (Op == OO_Exclaim ||
4071 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004072 Op == OO_PipePipe),
4073 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004074 }
4075
4076 bool isComparison = false;
4077 switch (Op) {
4078 case OO_None:
4079 case NUM_OVERLOADED_OPERATORS:
4080 assert(false && "Expected an overloaded operator");
4081 break;
4082
Douglas Gregord08452f2008-11-19 15:42:04 +00004083 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004084 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004085 goto UnaryStar;
4086 else
4087 goto BinaryStar;
4088 break;
4089
4090 case OO_Plus: // '+' is either unary or binary
4091 if (NumArgs == 1)
4092 goto UnaryPlus;
4093 else
4094 goto BinaryPlus;
4095 break;
4096
4097 case OO_Minus: // '-' is either unary or binary
4098 if (NumArgs == 1)
4099 goto UnaryMinus;
4100 else
4101 goto BinaryMinus;
4102 break;
4103
4104 case OO_Amp: // '&' is either unary or binary
4105 if (NumArgs == 1)
4106 goto UnaryAmp;
4107 else
4108 goto BinaryAmp;
4109
4110 case OO_PlusPlus:
4111 case OO_MinusMinus:
4112 // C++ [over.built]p3:
4113 //
4114 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4115 // is either volatile or empty, there exist candidate operator
4116 // functions of the form
4117 //
4118 // VQ T& operator++(VQ T&);
4119 // T operator++(VQ T&, int);
4120 //
4121 // C++ [over.built]p4:
4122 //
4123 // For every pair (T, VQ), where T is an arithmetic type other
4124 // than bool, and VQ is either volatile or empty, there exist
4125 // candidate operator functions of the form
4126 //
4127 // VQ T& operator--(VQ T&);
4128 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004129 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004130 Arith < NumArithmeticTypes; ++Arith) {
4131 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004132 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004133 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004134
4135 // Non-volatile version.
4136 if (NumArgs == 1)
4137 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4138 else
4139 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004140 // heuristic to reduce number of builtin candidates in the set.
4141 // Add volatile version only if there are conversions to a volatile type.
4142 if (VisibleTypeConversionsQuals.hasVolatile()) {
4143 // Volatile version
4144 ParamTypes[0]
4145 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4146 if (NumArgs == 1)
4147 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4148 else
4149 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4150 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004151 }
4152
4153 // C++ [over.built]p5:
4154 //
4155 // For every pair (T, VQ), where T is a cv-qualified or
4156 // cv-unqualified object type, and VQ is either volatile or
4157 // empty, there exist candidate operator functions of the form
4158 //
4159 // T*VQ& operator++(T*VQ&);
4160 // T*VQ& operator--(T*VQ&);
4161 // T* operator++(T*VQ&, int);
4162 // T* operator--(T*VQ&, int);
4163 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4164 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4165 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004166 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004167 continue;
4168
Mike Stump11289f42009-09-09 15:08:12 +00004169 QualType ParamTypes[2] = {
4170 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004171 };
Mike Stump11289f42009-09-09 15:08:12 +00004172
Douglas Gregord08452f2008-11-19 15:42:04 +00004173 // Without volatile
4174 if (NumArgs == 1)
4175 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4176 else
4177 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4178
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004179 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4180 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004181 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004182 ParamTypes[0]
4183 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004184 if (NumArgs == 1)
4185 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4186 else
4187 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4188 }
4189 }
4190 break;
4191
4192 UnaryStar:
4193 // C++ [over.built]p6:
4194 // For every cv-qualified or cv-unqualified object type T, there
4195 // exist candidate operator functions of the form
4196 //
4197 // T& operator*(T*);
4198 //
4199 // C++ [over.built]p7:
4200 // For every function type T, there exist candidate operator
4201 // functions of the form
4202 // T& operator*(T*);
4203 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4204 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4205 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004206 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004207 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004208 &ParamTy, Args, 1, CandidateSet);
4209 }
4210 break;
4211
4212 UnaryPlus:
4213 // C++ [over.built]p8:
4214 // For every type T, there exist candidate operator functions of
4215 // the form
4216 //
4217 // T* operator+(T*);
4218 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4219 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4220 QualType ParamTy = *Ptr;
4221 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
Douglas Gregord08452f2008-11-19 15:42:04 +00004224 // Fall through
4225
4226 UnaryMinus:
4227 // C++ [over.built]p9:
4228 // For every promoted arithmetic type T, there exist candidate
4229 // operator functions of the form
4230 //
4231 // T operator+(T);
4232 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004233 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004234 Arith < LastPromotedArithmeticType; ++Arith) {
4235 QualType ArithTy = ArithmeticTypes[Arith];
4236 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4237 }
4238 break;
4239
4240 case OO_Tilde:
4241 // C++ [over.built]p10:
4242 // For every promoted integral type T, there exist candidate
4243 // operator functions of the form
4244 //
4245 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004246 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004247 Int < LastPromotedIntegralType; ++Int) {
4248 QualType IntTy = ArithmeticTypes[Int];
4249 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4250 }
4251 break;
4252
Douglas Gregora11693b2008-11-12 17:17:38 +00004253 case OO_New:
4254 case OO_Delete:
4255 case OO_Array_New:
4256 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004257 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004258 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004259 break;
4260
4261 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004262 UnaryAmp:
4263 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004264 // C++ [over.match.oper]p3:
4265 // -- For the operator ',', the unary operator '&', or the
4266 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004267 break;
4268
Douglas Gregor84605ae2009-08-24 13:43:27 +00004269 case OO_EqualEqual:
4270 case OO_ExclaimEqual:
4271 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004272 // For every pointer to member type T, there exist candidate operator
4273 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004274 //
4275 // bool operator==(T,T);
4276 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004277 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004278 MemPtr = CandidateTypes.member_pointer_begin(),
4279 MemPtrEnd = CandidateTypes.member_pointer_end();
4280 MemPtr != MemPtrEnd;
4281 ++MemPtr) {
4282 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4283 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4284 }
Mike Stump11289f42009-09-09 15:08:12 +00004285
Douglas Gregor84605ae2009-08-24 13:43:27 +00004286 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004287
Douglas Gregora11693b2008-11-12 17:17:38 +00004288 case OO_Less:
4289 case OO_Greater:
4290 case OO_LessEqual:
4291 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004292 // C++ [over.built]p15:
4293 //
4294 // For every pointer or enumeration type T, there exist
4295 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004296 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004297 // bool operator<(T, T);
4298 // bool operator>(T, T);
4299 // bool operator<=(T, T);
4300 // bool operator>=(T, T);
4301 // bool operator==(T, T);
4302 // bool operator!=(T, T);
4303 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4304 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4305 QualType ParamTypes[2] = { *Ptr, *Ptr };
4306 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4307 }
Mike Stump11289f42009-09-09 15:08:12 +00004308 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004309 = CandidateTypes.enumeration_begin();
4310 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4311 QualType ParamTypes[2] = { *Enum, *Enum };
4312 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4313 }
4314
4315 // Fall through.
4316 isComparison = true;
4317
Douglas Gregord08452f2008-11-19 15:42:04 +00004318 BinaryPlus:
4319 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004320 if (!isComparison) {
4321 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4322
4323 // C++ [over.built]p13:
4324 //
4325 // For every cv-qualified or cv-unqualified object type T
4326 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004327 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004328 // T* operator+(T*, ptrdiff_t);
4329 // T& operator[](T*, ptrdiff_t); [BELOW]
4330 // T* operator-(T*, ptrdiff_t);
4331 // T* operator+(ptrdiff_t, T*);
4332 // T& operator[](ptrdiff_t, T*); [BELOW]
4333 //
4334 // C++ [over.built]p14:
4335 //
4336 // For every T, where T is a pointer to object type, there
4337 // exist candidate operator functions of the form
4338 //
4339 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004340 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004341 = CandidateTypes.pointer_begin();
4342 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4343 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4344
4345 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4346 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4347
4348 if (Op == OO_Plus) {
4349 // T* operator+(ptrdiff_t, T*);
4350 ParamTypes[0] = ParamTypes[1];
4351 ParamTypes[1] = *Ptr;
4352 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4353 } else {
4354 // ptrdiff_t operator-(T, T);
4355 ParamTypes[1] = *Ptr;
4356 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4357 Args, 2, CandidateSet);
4358 }
4359 }
4360 }
4361 // Fall through
4362
Douglas Gregora11693b2008-11-12 17:17:38 +00004363 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004364 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004365 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004366 // C++ [over.built]p12:
4367 //
4368 // For every pair of promoted arithmetic types L and R, there
4369 // exist candidate operator functions of the form
4370 //
4371 // LR operator*(L, R);
4372 // LR operator/(L, R);
4373 // LR operator+(L, R);
4374 // LR operator-(L, R);
4375 // bool operator<(L, R);
4376 // bool operator>(L, R);
4377 // bool operator<=(L, R);
4378 // bool operator>=(L, R);
4379 // bool operator==(L, R);
4380 // bool operator!=(L, R);
4381 //
4382 // where LR is the result of the usual arithmetic conversions
4383 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004384 //
4385 // C++ [over.built]p24:
4386 //
4387 // For every pair of promoted arithmetic types L and R, there exist
4388 // candidate operator functions of the form
4389 //
4390 // LR operator?(bool, L, R);
4391 //
4392 // where LR is the result of the usual arithmetic conversions
4393 // between types L and R.
4394 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004395 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004396 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004397 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004398 Right < LastPromotedArithmeticType; ++Right) {
4399 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004400 QualType Result
4401 = isComparison
4402 ? Context.BoolTy
4403 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004404 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4405 }
4406 }
4407 break;
4408
4409 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004410 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004411 case OO_Caret:
4412 case OO_Pipe:
4413 case OO_LessLess:
4414 case OO_GreaterGreater:
4415 // C++ [over.built]p17:
4416 //
4417 // For every pair of promoted integral types L and R, there
4418 // exist candidate operator functions of the form
4419 //
4420 // LR operator%(L, R);
4421 // LR operator&(L, R);
4422 // LR operator^(L, R);
4423 // LR operator|(L, R);
4424 // L operator<<(L, R);
4425 // L operator>>(L, R);
4426 //
4427 // where LR is the result of the usual arithmetic conversions
4428 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004429 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004430 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004431 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004432 Right < LastPromotedIntegralType; ++Right) {
4433 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4434 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4435 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004436 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004437 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4438 }
4439 }
4440 break;
4441
4442 case OO_Equal:
4443 // C++ [over.built]p20:
4444 //
4445 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004446 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004447 // empty, there exist candidate operator functions of the form
4448 //
4449 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004450 for (BuiltinCandidateTypeSet::iterator
4451 Enum = CandidateTypes.enumeration_begin(),
4452 EnumEnd = CandidateTypes.enumeration_end();
4453 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004454 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004455 CandidateSet);
4456 for (BuiltinCandidateTypeSet::iterator
4457 MemPtr = CandidateTypes.member_pointer_begin(),
4458 MemPtrEnd = CandidateTypes.member_pointer_end();
4459 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004460 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004461 CandidateSet);
4462 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004463
4464 case OO_PlusEqual:
4465 case OO_MinusEqual:
4466 // C++ [over.built]p19:
4467 //
4468 // For every pair (T, VQ), where T is any type and VQ is either
4469 // volatile or empty, there exist candidate operator functions
4470 // of the form
4471 //
4472 // T*VQ& operator=(T*VQ&, T*);
4473 //
4474 // C++ [over.built]p21:
4475 //
4476 // For every pair (T, VQ), where T is a cv-qualified or
4477 // cv-unqualified object type and VQ is either volatile or
4478 // empty, there exist candidate operator functions of the form
4479 //
4480 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4481 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4482 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4483 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4484 QualType ParamTypes[2];
4485 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4486
4487 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004488 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004489 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4490 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004491
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004492 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4493 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004494 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004495 ParamTypes[0]
4496 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004497 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4498 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004499 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004500 }
4501 // Fall through.
4502
4503 case OO_StarEqual:
4504 case OO_SlashEqual:
4505 // C++ [over.built]p18:
4506 //
4507 // For every triple (L, VQ, R), where L is an arithmetic type,
4508 // VQ is either volatile or empty, and R is a promoted
4509 // arithmetic type, there exist candidate operator functions of
4510 // the form
4511 //
4512 // VQ L& operator=(VQ L&, R);
4513 // VQ L& operator*=(VQ L&, R);
4514 // VQ L& operator/=(VQ L&, R);
4515 // VQ L& operator+=(VQ L&, R);
4516 // VQ L& operator-=(VQ L&, R);
4517 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004518 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004519 Right < LastPromotedArithmeticType; ++Right) {
4520 QualType ParamTypes[2];
4521 ParamTypes[1] = ArithmeticTypes[Right];
4522
4523 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004524 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004525 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4526 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004527
4528 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004529 if (VisibleTypeConversionsQuals.hasVolatile()) {
4530 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4531 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4532 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4533 /*IsAssigmentOperator=*/Op == OO_Equal);
4534 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004535 }
4536 }
4537 break;
4538
4539 case OO_PercentEqual:
4540 case OO_LessLessEqual:
4541 case OO_GreaterGreaterEqual:
4542 case OO_AmpEqual:
4543 case OO_CaretEqual:
4544 case OO_PipeEqual:
4545 // C++ [over.built]p22:
4546 //
4547 // For every triple (L, VQ, R), where L is an integral type, VQ
4548 // is either volatile or empty, and R is a promoted integral
4549 // type, there exist candidate operator functions of the form
4550 //
4551 // VQ L& operator%=(VQ L&, R);
4552 // VQ L& operator<<=(VQ L&, R);
4553 // VQ L& operator>>=(VQ L&, R);
4554 // VQ L& operator&=(VQ L&, R);
4555 // VQ L& operator^=(VQ L&, R);
4556 // VQ L& operator|=(VQ L&, R);
4557 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004558 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004559 Right < LastPromotedIntegralType; ++Right) {
4560 QualType ParamTypes[2];
4561 ParamTypes[1] = ArithmeticTypes[Right];
4562
4563 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004564 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004565 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004566 if (VisibleTypeConversionsQuals.hasVolatile()) {
4567 // Add this built-in operator as a candidate (VQ is 'volatile').
4568 ParamTypes[0] = ArithmeticTypes[Left];
4569 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4570 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4571 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4572 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004573 }
4574 }
4575 break;
4576
Douglas Gregord08452f2008-11-19 15:42:04 +00004577 case OO_Exclaim: {
4578 // C++ [over.operator]p23:
4579 //
4580 // There also exist candidate operator functions of the form
4581 //
Mike Stump11289f42009-09-09 15:08:12 +00004582 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004583 // bool operator&&(bool, bool); [BELOW]
4584 // bool operator||(bool, bool); [BELOW]
4585 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004586 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4587 /*IsAssignmentOperator=*/false,
4588 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004589 break;
4590 }
4591
Douglas Gregora11693b2008-11-12 17:17:38 +00004592 case OO_AmpAmp:
4593 case OO_PipePipe: {
4594 // C++ [over.operator]p23:
4595 //
4596 // There also exist candidate operator functions of the form
4597 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004598 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004599 // bool operator&&(bool, bool);
4600 // bool operator||(bool, bool);
4601 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004602 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4603 /*IsAssignmentOperator=*/false,
4604 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004605 break;
4606 }
4607
4608 case OO_Subscript:
4609 // C++ [over.built]p13:
4610 //
4611 // For every cv-qualified or cv-unqualified object type T there
4612 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004613 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004614 // T* operator+(T*, ptrdiff_t); [ABOVE]
4615 // T& operator[](T*, ptrdiff_t);
4616 // T* operator-(T*, ptrdiff_t); [ABOVE]
4617 // T* operator+(ptrdiff_t, T*); [ABOVE]
4618 // T& operator[](ptrdiff_t, T*);
4619 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4620 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4621 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004622 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004623 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004624
4625 // T& operator[](T*, ptrdiff_t)
4626 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4627
4628 // T& operator[](ptrdiff_t, T*);
4629 ParamTypes[0] = ParamTypes[1];
4630 ParamTypes[1] = *Ptr;
4631 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4632 }
4633 break;
4634
4635 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004636 // C++ [over.built]p11:
4637 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4638 // C1 is the same type as C2 or is a derived class of C2, T is an object
4639 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4640 // there exist candidate operator functions of the form
4641 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4642 // where CV12 is the union of CV1 and CV2.
4643 {
4644 for (BuiltinCandidateTypeSet::iterator Ptr =
4645 CandidateTypes.pointer_begin();
4646 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4647 QualType C1Ty = (*Ptr);
4648 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004649 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004650 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004651 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004652 if (!isa<RecordType>(C1))
4653 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004654 // heuristic to reduce number of builtin candidates in the set.
4655 // Add volatile/restrict version only if there are conversions to a
4656 // volatile/restrict type.
4657 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4658 continue;
4659 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4660 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004661 }
4662 for (BuiltinCandidateTypeSet::iterator
4663 MemPtr = CandidateTypes.member_pointer_begin(),
4664 MemPtrEnd = CandidateTypes.member_pointer_end();
4665 MemPtr != MemPtrEnd; ++MemPtr) {
4666 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4667 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004668 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004669 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4670 break;
4671 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4672 // build CV12 T&
4673 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004674 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4675 T.isVolatileQualified())
4676 continue;
4677 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4678 T.isRestrictQualified())
4679 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004680 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004681 QualType ResultTy = Context.getLValueReferenceType(T);
4682 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4683 }
4684 }
4685 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004686 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004687
4688 case OO_Conditional:
4689 // Note that we don't consider the first argument, since it has been
4690 // contextually converted to bool long ago. The candidates below are
4691 // therefore added as binary.
4692 //
4693 // C++ [over.built]p24:
4694 // For every type T, where T is a pointer or pointer-to-member type,
4695 // there exist candidate operator functions of the form
4696 //
4697 // T operator?(bool, T, T);
4698 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004699 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4700 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4701 QualType ParamTypes[2] = { *Ptr, *Ptr };
4702 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4703 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004704 for (BuiltinCandidateTypeSet::iterator Ptr =
4705 CandidateTypes.member_pointer_begin(),
4706 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4707 QualType ParamTypes[2] = { *Ptr, *Ptr };
4708 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4709 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004710 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004711 }
4712}
4713
Douglas Gregore254f902009-02-04 00:32:51 +00004714/// \brief Add function candidates found via argument-dependent lookup
4715/// to the set of overloading candidates.
4716///
4717/// This routine performs argument-dependent name lookup based on the
4718/// given function name (which may also be an operator name) and adds
4719/// all of the overload candidates found by ADL to the overload
4720/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004721void
Douglas Gregore254f902009-02-04 00:32:51 +00004722Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004723 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004724 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004725 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004726 OverloadCandidateSet& CandidateSet,
4727 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004728 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004729
John McCall91f61fc2010-01-26 06:04:06 +00004730 // FIXME: This approach for uniquing ADL results (and removing
4731 // redundant candidates from the set) relies on pointer-equality,
4732 // which means we need to key off the canonical decl. However,
4733 // always going back to the canonical decl might not get us the
4734 // right set of default arguments. What default arguments are
4735 // we supposed to consider on ADL candidates, anyway?
4736
Douglas Gregorcabea402009-09-22 15:41:20 +00004737 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004738 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004739
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004740 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004741 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4742 CandEnd = CandidateSet.end();
4743 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004744 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004745 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004746 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004747 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004748 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004749
4750 // For each of the ADL candidates we found, add it to the overload
4751 // set.
John McCall8fe68082010-01-26 07:16:45 +00004752 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004753 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004754 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004755 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004756 continue;
4757
John McCalla0296f72010-03-19 07:35:19 +00004758 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004759 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004760 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004761 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004762 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004763 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004764 }
Douglas Gregore254f902009-02-04 00:32:51 +00004765}
4766
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004767/// isBetterOverloadCandidate - Determines whether the first overload
4768/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004769bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004770Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004771 const OverloadCandidate& Cand2,
4772 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004773 // Define viable functions to be better candidates than non-viable
4774 // functions.
4775 if (!Cand2.Viable)
4776 return Cand1.Viable;
4777 else if (!Cand1.Viable)
4778 return false;
4779
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004780 // C++ [over.match.best]p1:
4781 //
4782 // -- if F is a static member function, ICS1(F) is defined such
4783 // that ICS1(F) is neither better nor worse than ICS1(G) for
4784 // any function G, and, symmetrically, ICS1(G) is neither
4785 // better nor worse than ICS1(F).
4786 unsigned StartArg = 0;
4787 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4788 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004789
Douglas Gregord3cb3562009-07-07 23:38:56 +00004790 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004791 // A viable function F1 is defined to be a better function than another
4792 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004793 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004794 unsigned NumArgs = Cand1.Conversions.size();
4795 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4796 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004797 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004798 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4799 Cand2.Conversions[ArgIdx])) {
4800 case ImplicitConversionSequence::Better:
4801 // Cand1 has a better conversion sequence.
4802 HasBetterConversion = true;
4803 break;
4804
4805 case ImplicitConversionSequence::Worse:
4806 // Cand1 can't be better than Cand2.
4807 return false;
4808
4809 case ImplicitConversionSequence::Indistinguishable:
4810 // Do nothing.
4811 break;
4812 }
4813 }
4814
Mike Stump11289f42009-09-09 15:08:12 +00004815 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004816 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004817 if (HasBetterConversion)
4818 return true;
4819
Mike Stump11289f42009-09-09 15:08:12 +00004820 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004821 // specialization, or, if not that,
4822 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4823 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4824 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004825
4826 // -- F1 and F2 are function template specializations, and the function
4827 // template for F1 is more specialized than the template for F2
4828 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004829 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004830 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4831 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004832 if (FunctionTemplateDecl *BetterTemplate
4833 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4834 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004835 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004836 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4837 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004838 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004839
Douglas Gregora1f013e2008-11-07 22:36:19 +00004840 // -- the context is an initialization by user-defined conversion
4841 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4842 // from the return type of F1 to the destination type (i.e.,
4843 // the type of the entity being initialized) is a better
4844 // conversion sequence than the standard conversion sequence
4845 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004846 if (Cand1.Function && Cand2.Function &&
4847 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004848 isa<CXXConversionDecl>(Cand2.Function)) {
4849 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4850 Cand2.FinalConversion)) {
4851 case ImplicitConversionSequence::Better:
4852 // Cand1 has a better conversion sequence.
4853 return true;
4854
4855 case ImplicitConversionSequence::Worse:
4856 // Cand1 can't be better than Cand2.
4857 return false;
4858
4859 case ImplicitConversionSequence::Indistinguishable:
4860 // Do nothing
4861 break;
4862 }
4863 }
4864
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004865 return false;
4866}
4867
Mike Stump11289f42009-09-09 15:08:12 +00004868/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004869/// within an overload candidate set.
4870///
4871/// \param CandidateSet the set of candidate functions.
4872///
4873/// \param Loc the location of the function name (or operator symbol) for
4874/// which overload resolution occurs.
4875///
Mike Stump11289f42009-09-09 15:08:12 +00004876/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004877/// function, Best points to the candidate function found.
4878///
4879/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004880OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4881 SourceLocation Loc,
4882 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004883 // Find the best viable function.
4884 Best = CandidateSet.end();
4885 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4886 Cand != CandidateSet.end(); ++Cand) {
4887 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004888 if (Best == CandidateSet.end() ||
4889 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004890 Best = Cand;
4891 }
4892 }
4893
4894 // If we didn't find any viable functions, abort.
4895 if (Best == CandidateSet.end())
4896 return OR_No_Viable_Function;
4897
4898 // Make sure that this function is better than every other viable
4899 // function. If not, we have an ambiguity.
4900 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4901 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004902 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004903 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004904 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004905 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004906 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004907 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004908 }
Mike Stump11289f42009-09-09 15:08:12 +00004909
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004910 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004911 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004912 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004913 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004914 return OR_Deleted;
4915
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004916 // C++ [basic.def.odr]p2:
4917 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004918 // when referred to from a potentially-evaluated expression. [Note: this
4919 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004920 // (clause 13), user-defined conversions (12.3.2), allocation function for
4921 // placement new (5.3.4), as well as non-default initialization (8.5).
4922 if (Best->Function)
4923 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004924 return OR_Success;
4925}
4926
John McCall53262c92010-01-12 02:15:36 +00004927namespace {
4928
4929enum OverloadCandidateKind {
4930 oc_function,
4931 oc_method,
4932 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004933 oc_function_template,
4934 oc_method_template,
4935 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004936 oc_implicit_default_constructor,
4937 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004938 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004939};
4940
John McCalle1ac8d12010-01-13 00:25:19 +00004941OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4942 FunctionDecl *Fn,
4943 std::string &Description) {
4944 bool isTemplate = false;
4945
4946 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4947 isTemplate = true;
4948 Description = S.getTemplateArgumentBindingsText(
4949 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4950 }
John McCallfd0b2f82010-01-06 09:43:14 +00004951
4952 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004953 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004954 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004955
John McCall53262c92010-01-12 02:15:36 +00004956 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4957 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004958 }
4959
4960 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4961 // This actually gets spelled 'candidate function' for now, but
4962 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004963 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004964 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004965
4966 assert(Meth->isCopyAssignment()
4967 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004968 return oc_implicit_copy_assignment;
4969 }
4970
John McCalle1ac8d12010-01-13 00:25:19 +00004971 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004972}
4973
4974} // end anonymous namespace
4975
4976// Notes the location of an overload candidate.
4977void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004978 std::string FnDesc;
4979 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4980 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4981 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004982}
4983
John McCall0d1da222010-01-12 00:44:57 +00004984/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4985/// "lead" diagnostic; it will be given two arguments, the source and
4986/// target types of the conversion.
4987void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4988 SourceLocation CaretLoc,
4989 const PartialDiagnostic &PDiag) {
4990 Diag(CaretLoc, PDiag)
4991 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4992 for (AmbiguousConversionSequence::const_iterator
4993 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4994 NoteOverloadCandidate(*I);
4995 }
John McCall12f97bc2010-01-08 04:41:39 +00004996}
4997
John McCall0d1da222010-01-12 00:44:57 +00004998namespace {
4999
John McCall6a61b522010-01-13 09:16:55 +00005000void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5001 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5002 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005003 assert(Cand->Function && "for now, candidate must be a function");
5004 FunctionDecl *Fn = Cand->Function;
5005
5006 // There's a conversion slot for the object argument if this is a
5007 // non-constructor method. Note that 'I' corresponds the
5008 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005009 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005010 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005011 if (I == 0)
5012 isObjectArgument = true;
5013 else
5014 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005015 }
5016
John McCalle1ac8d12010-01-13 00:25:19 +00005017 std::string FnDesc;
5018 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5019
John McCall6a61b522010-01-13 09:16:55 +00005020 Expr *FromExpr = Conv.Bad.FromExpr;
5021 QualType FromTy = Conv.Bad.getFromType();
5022 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005023
John McCallfb7ad0f2010-02-02 02:42:52 +00005024 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005025 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005026 Expr *E = FromExpr->IgnoreParens();
5027 if (isa<UnaryOperator>(E))
5028 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005029 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005030
5031 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5032 << (unsigned) FnKind << FnDesc
5033 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5034 << ToTy << Name << I+1;
5035 return;
5036 }
5037
John McCall6d174642010-01-23 08:10:49 +00005038 // Do some hand-waving analysis to see if the non-viability is due
5039 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005040 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5041 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5042 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5043 CToTy = RT->getPointeeType();
5044 else {
5045 // TODO: detect and diagnose the full richness of const mismatches.
5046 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5047 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5048 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5049 }
5050
5051 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5052 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5053 // It is dumb that we have to do this here.
5054 while (isa<ArrayType>(CFromTy))
5055 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5056 while (isa<ArrayType>(CToTy))
5057 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5058
5059 Qualifiers FromQs = CFromTy.getQualifiers();
5060 Qualifiers ToQs = CToTy.getQualifiers();
5061
5062 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5063 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5064 << (unsigned) FnKind << FnDesc
5065 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5066 << FromTy
5067 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5068 << (unsigned) isObjectArgument << I+1;
5069 return;
5070 }
5071
5072 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5073 assert(CVR && "unexpected qualifiers mismatch");
5074
5075 if (isObjectArgument) {
5076 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5077 << (unsigned) FnKind << FnDesc
5078 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5079 << FromTy << (CVR - 1);
5080 } else {
5081 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5082 << (unsigned) FnKind << FnDesc
5083 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5084 << FromTy << (CVR - 1) << I+1;
5085 }
5086 return;
5087 }
5088
John McCall6d174642010-01-23 08:10:49 +00005089 // Diagnose references or pointers to incomplete types differently,
5090 // since it's far from impossible that the incompleteness triggered
5091 // the failure.
5092 QualType TempFromTy = FromTy.getNonReferenceType();
5093 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5094 TempFromTy = PTy->getPointeeType();
5095 if (TempFromTy->isIncompleteType()) {
5096 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5097 << (unsigned) FnKind << FnDesc
5098 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5099 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5100 return;
5101 }
5102
John McCall47000992010-01-14 03:28:57 +00005103 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5105 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005106 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005107 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005108}
5109
5110void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5111 unsigned NumFormalArgs) {
5112 // TODO: treat calls to a missing default constructor as a special case
5113
5114 FunctionDecl *Fn = Cand->Function;
5115 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5116
5117 unsigned MinParams = Fn->getMinRequiredArguments();
5118
5119 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005120 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005121 unsigned mode, modeCount;
5122 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005123 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5124 (Cand->FailureKind == ovl_fail_bad_deduction &&
5125 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005126 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5127 mode = 0; // "at least"
5128 else
5129 mode = 2; // "exactly"
5130 modeCount = MinParams;
5131 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005132 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5133 (Cand->FailureKind == ovl_fail_bad_deduction &&
5134 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005135 if (MinParams != FnTy->getNumArgs())
5136 mode = 1; // "at most"
5137 else
5138 mode = 2; // "exactly"
5139 modeCount = FnTy->getNumArgs();
5140 }
5141
5142 std::string Description;
5143 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5144
5145 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005146 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5147 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005148}
5149
John McCall8b9ed552010-02-01 18:53:26 +00005150/// Diagnose a failed template-argument deduction.
5151void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5152 Expr **Args, unsigned NumArgs) {
5153 FunctionDecl *Fn = Cand->Function; // pattern
5154
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005155 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005156 NamedDecl *ParamD;
5157 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5158 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5159 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005160 switch (Cand->DeductionFailure.Result) {
5161 case Sema::TDK_Success:
5162 llvm_unreachable("TDK_success while diagnosing bad deduction");
5163
5164 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005165 assert(ParamD && "no parameter found for incomplete deduction result");
5166 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5167 << ParamD->getDeclName();
5168 return;
5169 }
5170
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005171 case Sema::TDK_Inconsistent:
5172 case Sema::TDK_InconsistentQuals: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005173 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005174 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005175 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005176 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005177 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005178 which = 1;
5179 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005180 which = 2;
5181 }
5182
5183 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5184 << which << ParamD->getDeclName()
5185 << *Cand->DeductionFailure.getFirstArg()
5186 << *Cand->DeductionFailure.getSecondArg();
5187 return;
5188 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005189
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005190 case Sema::TDK_InvalidExplicitArguments:
5191 assert(ParamD && "no parameter found for invalid explicit arguments");
5192 if (ParamD->getDeclName())
5193 S.Diag(Fn->getLocation(),
5194 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5195 << ParamD->getDeclName();
5196 else {
5197 int index = 0;
5198 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5199 index = TTP->getIndex();
5200 else if (NonTypeTemplateParmDecl *NTTP
5201 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5202 index = NTTP->getIndex();
5203 else
5204 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5205 S.Diag(Fn->getLocation(),
5206 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5207 << (index + 1);
5208 }
5209 return;
5210
Douglas Gregor02eb4832010-05-08 18:13:28 +00005211 case Sema::TDK_TooManyArguments:
5212 case Sema::TDK_TooFewArguments:
5213 DiagnoseArityMismatch(S, Cand, NumArgs);
5214 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005215
5216 case Sema::TDK_InstantiationDepth:
5217 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5218 return;
5219
5220 case Sema::TDK_SubstitutionFailure: {
5221 std::string ArgString;
5222 if (TemplateArgumentList *Args
5223 = Cand->DeductionFailure.getTemplateArgumentList())
5224 ArgString = S.getTemplateArgumentBindingsText(
5225 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5226 *Args);
5227 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5228 << ArgString;
5229 return;
5230 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005231
John McCall8b9ed552010-02-01 18:53:26 +00005232 // TODO: diagnose these individually, then kill off
5233 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005234 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005235 case Sema::TDK_FailedOverloadResolution:
5236 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5237 return;
5238 }
5239}
5240
5241/// Generates a 'note' diagnostic for an overload candidate. We've
5242/// already generated a primary error at the call site.
5243///
5244/// It really does need to be a single diagnostic with its caret
5245/// pointed at the candidate declaration. Yes, this creates some
5246/// major challenges of technical writing. Yes, this makes pointing
5247/// out problems with specific arguments quite awkward. It's still
5248/// better than generating twenty screens of text for every failed
5249/// overload.
5250///
5251/// It would be great to be able to express per-candidate problems
5252/// more richly for those diagnostic clients that cared, but we'd
5253/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005254void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5255 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005256 FunctionDecl *Fn = Cand->Function;
5257
John McCall12f97bc2010-01-08 04:41:39 +00005258 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005259 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005260 std::string FnDesc;
5261 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005262
5263 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005264 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005265 return;
John McCall12f97bc2010-01-08 04:41:39 +00005266 }
5267
John McCalle1ac8d12010-01-13 00:25:19 +00005268 // We don't really have anything else to say about viable candidates.
5269 if (Cand->Viable) {
5270 S.NoteOverloadCandidate(Fn);
5271 return;
5272 }
John McCall0d1da222010-01-12 00:44:57 +00005273
John McCall6a61b522010-01-13 09:16:55 +00005274 switch (Cand->FailureKind) {
5275 case ovl_fail_too_many_arguments:
5276 case ovl_fail_too_few_arguments:
5277 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005278
John McCall6a61b522010-01-13 09:16:55 +00005279 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005280 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5281
John McCallfe796dd2010-01-23 05:17:32 +00005282 case ovl_fail_trivial_conversion:
5283 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005284 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005285 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005286
John McCall65eb8792010-02-25 01:37:24 +00005287 case ovl_fail_bad_conversion: {
5288 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5289 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005290 if (Cand->Conversions[I].isBad())
5291 return DiagnoseBadConversion(S, Cand, I);
5292
5293 // FIXME: this currently happens when we're called from SemaInit
5294 // when user-conversion overload fails. Figure out how to handle
5295 // those conditions and diagnose them well.
5296 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005297 }
John McCall65eb8792010-02-25 01:37:24 +00005298 }
John McCalld3224162010-01-08 00:58:21 +00005299}
5300
5301void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5302 // Desugar the type of the surrogate down to a function type,
5303 // retaining as many typedefs as possible while still showing
5304 // the function type (and, therefore, its parameter types).
5305 QualType FnType = Cand->Surrogate->getConversionType();
5306 bool isLValueReference = false;
5307 bool isRValueReference = false;
5308 bool isPointer = false;
5309 if (const LValueReferenceType *FnTypeRef =
5310 FnType->getAs<LValueReferenceType>()) {
5311 FnType = FnTypeRef->getPointeeType();
5312 isLValueReference = true;
5313 } else if (const RValueReferenceType *FnTypeRef =
5314 FnType->getAs<RValueReferenceType>()) {
5315 FnType = FnTypeRef->getPointeeType();
5316 isRValueReference = true;
5317 }
5318 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5319 FnType = FnTypePtr->getPointeeType();
5320 isPointer = true;
5321 }
5322 // Desugar down to a function type.
5323 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5324 // Reconstruct the pointer/reference as appropriate.
5325 if (isPointer) FnType = S.Context.getPointerType(FnType);
5326 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5327 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5328
5329 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5330 << FnType;
5331}
5332
5333void NoteBuiltinOperatorCandidate(Sema &S,
5334 const char *Opc,
5335 SourceLocation OpLoc,
5336 OverloadCandidate *Cand) {
5337 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5338 std::string TypeStr("operator");
5339 TypeStr += Opc;
5340 TypeStr += "(";
5341 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5342 if (Cand->Conversions.size() == 1) {
5343 TypeStr += ")";
5344 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5345 } else {
5346 TypeStr += ", ";
5347 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5348 TypeStr += ")";
5349 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5350 }
5351}
5352
5353void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5354 OverloadCandidate *Cand) {
5355 unsigned NoOperands = Cand->Conversions.size();
5356 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5357 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005358 if (ICS.isBad()) break; // all meaningless after first invalid
5359 if (!ICS.isAmbiguous()) continue;
5360
5361 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005362 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005363 }
5364}
5365
John McCall3712d9e2010-01-15 23:32:50 +00005366SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5367 if (Cand->Function)
5368 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005369 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005370 return Cand->Surrogate->getLocation();
5371 return SourceLocation();
5372}
5373
John McCallad2587a2010-01-12 00:48:53 +00005374struct CompareOverloadCandidatesForDisplay {
5375 Sema &S;
5376 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005377
5378 bool operator()(const OverloadCandidate *L,
5379 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005380 // Fast-path this check.
5381 if (L == R) return false;
5382
John McCall12f97bc2010-01-08 04:41:39 +00005383 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005384 if (L->Viable) {
5385 if (!R->Viable) return true;
5386
5387 // TODO: introduce a tri-valued comparison for overload
5388 // candidates. Would be more worthwhile if we had a sort
5389 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005390 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5391 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005392 } else if (R->Viable)
5393 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005394
John McCall3712d9e2010-01-15 23:32:50 +00005395 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005396
John McCall3712d9e2010-01-15 23:32:50 +00005397 // Criteria by which we can sort non-viable candidates:
5398 if (!L->Viable) {
5399 // 1. Arity mismatches come after other candidates.
5400 if (L->FailureKind == ovl_fail_too_many_arguments ||
5401 L->FailureKind == ovl_fail_too_few_arguments)
5402 return false;
5403 if (R->FailureKind == ovl_fail_too_many_arguments ||
5404 R->FailureKind == ovl_fail_too_few_arguments)
5405 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005406
John McCallfe796dd2010-01-23 05:17:32 +00005407 // 2. Bad conversions come first and are ordered by the number
5408 // of bad conversions and quality of good conversions.
5409 if (L->FailureKind == ovl_fail_bad_conversion) {
5410 if (R->FailureKind != ovl_fail_bad_conversion)
5411 return true;
5412
5413 // If there's any ordering between the defined conversions...
5414 // FIXME: this might not be transitive.
5415 assert(L->Conversions.size() == R->Conversions.size());
5416
5417 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005418 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5419 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005420 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5421 R->Conversions[I])) {
5422 case ImplicitConversionSequence::Better:
5423 leftBetter++;
5424 break;
5425
5426 case ImplicitConversionSequence::Worse:
5427 leftBetter--;
5428 break;
5429
5430 case ImplicitConversionSequence::Indistinguishable:
5431 break;
5432 }
5433 }
5434 if (leftBetter > 0) return true;
5435 if (leftBetter < 0) return false;
5436
5437 } else if (R->FailureKind == ovl_fail_bad_conversion)
5438 return false;
5439
John McCall3712d9e2010-01-15 23:32:50 +00005440 // TODO: others?
5441 }
5442
5443 // Sort everything else by location.
5444 SourceLocation LLoc = GetLocationForCandidate(L);
5445 SourceLocation RLoc = GetLocationForCandidate(R);
5446
5447 // Put candidates without locations (e.g. builtins) at the end.
5448 if (LLoc.isInvalid()) return false;
5449 if (RLoc.isInvalid()) return true;
5450
5451 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005452 }
5453};
5454
John McCallfe796dd2010-01-23 05:17:32 +00005455/// CompleteNonViableCandidate - Normally, overload resolution only
5456/// computes up to the first
5457void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5458 Expr **Args, unsigned NumArgs) {
5459 assert(!Cand->Viable);
5460
5461 // Don't do anything on failures other than bad conversion.
5462 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5463
5464 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005465 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005466 unsigned ConvCount = Cand->Conversions.size();
5467 while (true) {
5468 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5469 ConvIdx++;
5470 if (Cand->Conversions[ConvIdx - 1].isBad())
5471 break;
5472 }
5473
5474 if (ConvIdx == ConvCount)
5475 return;
5476
John McCall65eb8792010-02-25 01:37:24 +00005477 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5478 "remaining conversion is initialized?");
5479
Douglas Gregoradc7a702010-04-16 17:45:54 +00005480 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005481 // operation somehow.
5482 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005483
5484 const FunctionProtoType* Proto;
5485 unsigned ArgIdx = ConvIdx;
5486
5487 if (Cand->IsSurrogate) {
5488 QualType ConvType
5489 = Cand->Surrogate->getConversionType().getNonReferenceType();
5490 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5491 ConvType = ConvPtrType->getPointeeType();
5492 Proto = ConvType->getAs<FunctionProtoType>();
5493 ArgIdx--;
5494 } else if (Cand->Function) {
5495 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5496 if (isa<CXXMethodDecl>(Cand->Function) &&
5497 !isa<CXXConstructorDecl>(Cand->Function))
5498 ArgIdx--;
5499 } else {
5500 // Builtin binary operator with a bad first conversion.
5501 assert(ConvCount <= 3);
5502 for (; ConvIdx != ConvCount; ++ConvIdx)
5503 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005504 = TryCopyInitialization(S, Args[ConvIdx],
5505 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5506 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005507 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005508 return;
5509 }
5510
5511 // Fill in the rest of the conversions.
5512 unsigned NumArgsInProto = Proto->getNumArgs();
5513 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5514 if (ArgIdx < NumArgsInProto)
5515 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005516 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5517 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005518 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005519 else
5520 Cand->Conversions[ConvIdx].setEllipsis();
5521 }
5522}
5523
John McCalld3224162010-01-08 00:58:21 +00005524} // end anonymous namespace
5525
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005526/// PrintOverloadCandidates - When overload resolution fails, prints
5527/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005528/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005529void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005530Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005531 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005532 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005533 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005534 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005535 // Sort the candidates by viability and position. Sorting directly would
5536 // be prohibitive, so we make a set of pointers and sort those.
5537 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5538 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5539 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5540 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005541 Cand != LastCand; ++Cand) {
5542 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005543 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005544 else if (OCD == OCD_AllCandidates) {
5545 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5546 Cands.push_back(Cand);
5547 }
5548 }
5549
John McCallad2587a2010-01-12 00:48:53 +00005550 std::sort(Cands.begin(), Cands.end(),
5551 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005552
John McCall0d1da222010-01-12 00:44:57 +00005553 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005554
John McCall12f97bc2010-01-08 04:41:39 +00005555 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5556 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5557 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005558
John McCalld3224162010-01-08 00:58:21 +00005559 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005560 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005561 else if (Cand->IsSurrogate)
5562 NoteSurrogateCandidate(*this, Cand);
5563
5564 // This a builtin candidate. We do not, in general, want to list
5565 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005566 else if (Cand->Viable) {
5567 // Generally we only see ambiguities including viable builtin
5568 // operators if overload resolution got screwed up by an
5569 // ambiguous user-defined conversion.
5570 //
5571 // FIXME: It's quite possible for different conversions to see
5572 // different ambiguities, though.
5573 if (!ReportedAmbiguousConversions) {
5574 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5575 ReportedAmbiguousConversions = true;
5576 }
John McCalld3224162010-01-08 00:58:21 +00005577
John McCall0d1da222010-01-12 00:44:57 +00005578 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005579 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005580 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005581 }
5582}
5583
John McCalla0296f72010-03-19 07:35:19 +00005584static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005585 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005586 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005587
John McCalla0296f72010-03-19 07:35:19 +00005588 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005589}
5590
Douglas Gregorcd695e52008-11-10 20:40:00 +00005591/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5592/// an overloaded function (C++ [over.over]), where @p From is an
5593/// expression with overloaded function type and @p ToType is the type
5594/// we're trying to resolve to. For example:
5595///
5596/// @code
5597/// int f(double);
5598/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005599///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005600/// int (*pfd)(double) = f; // selects f(double)
5601/// @endcode
5602///
5603/// This routine returns the resulting FunctionDecl if it could be
5604/// resolved, and NULL otherwise. When @p Complain is true, this
5605/// routine will emit diagnostics if there is an error.
5606FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005607Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005608 bool Complain,
5609 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005610 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005611 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005612 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005613 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005614 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005615 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005616 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005617 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005618 FunctionType = MemTypePtr->getPointeeType();
5619 IsMember = true;
5620 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005621
Douglas Gregorcd695e52008-11-10 20:40:00 +00005622 // C++ [over.over]p1:
5623 // [...] [Note: any redundant set of parentheses surrounding the
5624 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005625 // C++ [over.over]p1:
5626 // [...] The overloaded function name can be preceded by the &
5627 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005628 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5629 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5630 if (OvlExpr->hasExplicitTemplateArgs()) {
5631 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5632 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005633 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005634
5635 // We expect a pointer or reference to function, or a function pointer.
5636 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5637 if (!FunctionType->isFunctionType()) {
5638 if (Complain)
5639 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5640 << OvlExpr->getName() << ToType;
5641
5642 return 0;
5643 }
5644
5645 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005646
Douglas Gregorcd695e52008-11-10 20:40:00 +00005647 // Look through all of the overloaded functions, searching for one
5648 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005649 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005650 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5651
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005652 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005653 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5654 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005655 // Look through any using declarations to find the underlying function.
5656 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5657
Douglas Gregorcd695e52008-11-10 20:40:00 +00005658 // C++ [over.over]p3:
5659 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005660 // targets of type "pointer-to-function" or "reference-to-function."
5661 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005662 // type "pointer-to-member-function."
5663 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005664
Mike Stump11289f42009-09-09 15:08:12 +00005665 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005666 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005667 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005668 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005669 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005670 // static when converting to member pointer.
5671 if (Method->isStatic() == IsMember)
5672 continue;
5673 } else if (IsMember)
5674 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005675
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005676 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005677 // If the name is a function template, template argument deduction is
5678 // done (14.8.2.2), and if the argument deduction succeeds, the
5679 // resulting template argument list is used to generate a single
5680 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005681 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005682 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005683 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005684 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005685 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005686 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005687 FunctionType, Specialization, Info)) {
5688 // FIXME: make a note of the failed deduction for diagnostics.
5689 (void)Result;
5690 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005691 // FIXME: If the match isn't exact, shouldn't we just drop this as
5692 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005693 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005694 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005695 Matches.push_back(std::make_pair(I.getPair(),
5696 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005697 }
John McCalld14a8642009-11-21 08:51:07 +00005698
5699 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005700 }
Mike Stump11289f42009-09-09 15:08:12 +00005701
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005702 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005703 // Skip non-static functions when converting to pointer, and static
5704 // when converting to member pointer.
5705 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005706 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005707
5708 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005709 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005710 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005711 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005712 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005713
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005714 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005715 QualType ResultTy;
5716 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5717 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5718 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005719 Matches.push_back(std::make_pair(I.getPair(),
5720 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005721 FoundNonTemplateFunction = true;
5722 }
Mike Stump11289f42009-09-09 15:08:12 +00005723 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005724 }
5725
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005726 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005727 if (Matches.empty()) {
5728 if (Complain) {
5729 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5730 << OvlExpr->getName() << FunctionType;
5731 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5732 E = OvlExpr->decls_end();
5733 I != E; ++I)
5734 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5735 NoteOverloadCandidate(F);
5736 }
5737
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005738 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005739 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005740 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005741 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005742 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005743 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005744 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005745 return Result;
5746 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005747
5748 // C++ [over.over]p4:
5749 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005750 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005751 // [...] and any given function template specialization F1 is
5752 // eliminated if the set contains a second function template
5753 // specialization whose function template is more specialized
5754 // than the function template of F1 according to the partial
5755 // ordering rules of 14.5.5.2.
5756
5757 // The algorithm specified above is quadratic. We instead use a
5758 // two-pass algorithm (similar to the one used to identify the
5759 // best viable function in an overload set) that identifies the
5760 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005761
5762 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5763 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5764 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005765
5766 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005767 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005768 TPOC_Other, From->getLocStart(),
5769 PDiag(),
5770 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005771 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005772 PDiag(diag::note_ovl_candidate)
5773 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005774 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005775 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005776 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005777 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00005778 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00005779 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5780 }
John McCall58cc69d2010-01-27 01:50:18 +00005781 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005782 }
Mike Stump11289f42009-09-09 15:08:12 +00005783
Douglas Gregorfae1d712009-09-26 03:56:17 +00005784 // [...] any function template specializations in the set are
5785 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005786 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005787 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005788 ++I;
5789 else {
John McCalla0296f72010-03-19 07:35:19 +00005790 Matches[I] = Matches[--N];
5791 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005792 }
5793 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005794
Mike Stump11289f42009-09-09 15:08:12 +00005795 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005796 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005797 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005798 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005799 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005800 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00005801 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00005802 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5803 }
John McCalla0296f72010-03-19 07:35:19 +00005804 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005805 }
Mike Stump11289f42009-09-09 15:08:12 +00005806
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005807 // FIXME: We should probably return the same thing that BestViableFunction
5808 // returns (even if we issue the diagnostics here).
5809 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005810 << Matches[0].second->getDeclName();
5811 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5812 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005813 return 0;
5814}
5815
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005816/// \brief Given an expression that refers to an overloaded function, try to
5817/// resolve that overloaded function expression down to a single function.
5818///
5819/// This routine can only resolve template-ids that refer to a single function
5820/// template, where that template-id refers to a single template whose template
5821/// arguments are either provided by the template-id or have defaults,
5822/// as described in C++0x [temp.arg.explicit]p3.
5823FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5824 // C++ [over.over]p1:
5825 // [...] [Note: any redundant set of parentheses surrounding the
5826 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005827 // C++ [over.over]p1:
5828 // [...] The overloaded function name can be preceded by the &
5829 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005830
5831 if (From->getType() != Context.OverloadTy)
5832 return 0;
5833
5834 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005835
5836 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005837 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005838 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005839
5840 TemplateArgumentListInfo ExplicitTemplateArgs;
5841 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005842
5843 // Look through all of the overloaded functions, searching for one
5844 // whose type matches exactly.
5845 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005846 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5847 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005848 // C++0x [temp.arg.explicit]p3:
5849 // [...] In contexts where deduction is done and fails, or in contexts
5850 // where deduction is not done, if a template argument list is
5851 // specified and it, along with any default template arguments,
5852 // identifies a single function template specialization, then the
5853 // template-id is an lvalue for the function template specialization.
5854 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5855
5856 // C++ [over.over]p2:
5857 // If the name is a function template, template argument deduction is
5858 // done (14.8.2.2), and if the argument deduction succeeds, the
5859 // resulting template argument list is used to generate a single
5860 // function template specialization, which is added to the set of
5861 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005862 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005863 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005864 if (TemplateDeductionResult Result
5865 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5866 Specialization, Info)) {
5867 // FIXME: make a note of the failed deduction for diagnostics.
5868 (void)Result;
5869 continue;
5870 }
5871
5872 // Multiple matches; we can't resolve to a single declaration.
5873 if (Matched)
5874 return 0;
5875
5876 Matched = Specialization;
5877 }
5878
5879 return Matched;
5880}
5881
Douglas Gregorcabea402009-09-22 15:41:20 +00005882/// \brief Add a single candidate to the overload set.
5883static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005884 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005885 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005886 Expr **Args, unsigned NumArgs,
5887 OverloadCandidateSet &CandidateSet,
5888 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005889 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005890 if (isa<UsingShadowDecl>(Callee))
5891 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5892
Douglas Gregorcabea402009-09-22 15:41:20 +00005893 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005894 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005895 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005896 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005897 return;
John McCalld14a8642009-11-21 08:51:07 +00005898 }
5899
5900 if (FunctionTemplateDecl *FuncTemplate
5901 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005902 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5903 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005904 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005905 return;
5906 }
5907
5908 assert(false && "unhandled case in overloaded call candidate");
5909
5910 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005911}
5912
5913/// \brief Add the overload candidates named by callee and/or found by argument
5914/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005915void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005916 Expr **Args, unsigned NumArgs,
5917 OverloadCandidateSet &CandidateSet,
5918 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005919
5920#ifndef NDEBUG
5921 // Verify that ArgumentDependentLookup is consistent with the rules
5922 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005923 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005924 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5925 // and let Y be the lookup set produced by argument dependent
5926 // lookup (defined as follows). If X contains
5927 //
5928 // -- a declaration of a class member, or
5929 //
5930 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005931 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005932 //
5933 // -- a declaration that is neither a function or a function
5934 // template
5935 //
5936 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005937
John McCall57500772009-12-16 12:17:52 +00005938 if (ULE->requiresADL()) {
5939 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5940 E = ULE->decls_end(); I != E; ++I) {
5941 assert(!(*I)->getDeclContext()->isRecord());
5942 assert(isa<UsingShadowDecl>(*I) ||
5943 !(*I)->getDeclContext()->isFunctionOrMethod());
5944 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005945 }
5946 }
5947#endif
5948
John McCall57500772009-12-16 12:17:52 +00005949 // It would be nice to avoid this copy.
5950 TemplateArgumentListInfo TABuffer;
5951 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5952 if (ULE->hasExplicitTemplateArgs()) {
5953 ULE->copyTemplateArgumentsInto(TABuffer);
5954 ExplicitTemplateArgs = &TABuffer;
5955 }
5956
5957 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5958 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005959 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005960 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005961 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005962
John McCall57500772009-12-16 12:17:52 +00005963 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005964 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5965 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005966 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005967 CandidateSet,
5968 PartialOverloading);
5969}
John McCalld681c392009-12-16 08:11:27 +00005970
John McCall57500772009-12-16 12:17:52 +00005971static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5972 Expr **Args, unsigned NumArgs) {
5973 Fn->Destroy(SemaRef.Context);
5974 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5975 Args[Arg]->Destroy(SemaRef.Context);
5976 return SemaRef.ExprError();
5977}
5978
John McCalld681c392009-12-16 08:11:27 +00005979/// Attempts to recover from a call where no functions were found.
5980///
5981/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005982static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005983BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005984 UnresolvedLookupExpr *ULE,
5985 SourceLocation LParenLoc,
5986 Expr **Args, unsigned NumArgs,
5987 SourceLocation *CommaLocs,
5988 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005989
5990 CXXScopeSpec SS;
5991 if (ULE->getQualifier()) {
5992 SS.setScopeRep(ULE->getQualifier());
5993 SS.setRange(ULE->getQualifierRange());
5994 }
5995
John McCall57500772009-12-16 12:17:52 +00005996 TemplateArgumentListInfo TABuffer;
5997 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5998 if (ULE->hasExplicitTemplateArgs()) {
5999 ULE->copyTemplateArgumentsInto(TABuffer);
6000 ExplicitTemplateArgs = &TABuffer;
6001 }
6002
John McCalld681c392009-12-16 08:11:27 +00006003 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6004 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006005 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall57500772009-12-16 12:17:52 +00006006 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00006007
John McCall57500772009-12-16 12:17:52 +00006008 assert(!R.empty() && "lookup results empty despite recovery");
6009
6010 // Build an implicit member call if appropriate. Just drop the
6011 // casts and such from the call, we don't really care.
6012 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6013 if ((*R.begin())->isCXXClassMember())
6014 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6015 else if (ExplicitTemplateArgs)
6016 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6017 else
6018 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6019
6020 if (NewFn.isInvalid())
6021 return Destroy(SemaRef, Fn, Args, NumArgs);
6022
6023 Fn->Destroy(SemaRef.Context);
6024
6025 // This shouldn't cause an infinite loop because we're giving it
6026 // an expression with non-empty lookup results, which should never
6027 // end up here.
6028 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6029 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6030 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006031}
Douglas Gregorcabea402009-09-22 15:41:20 +00006032
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006033/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006034/// (which eventually refers to the declaration Func) and the call
6035/// arguments Args/NumArgs, attempt to resolve the function call down
6036/// to a specific function. If overload resolution succeeds, returns
6037/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006038/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006039/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006040Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006041Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006042 SourceLocation LParenLoc,
6043 Expr **Args, unsigned NumArgs,
6044 SourceLocation *CommaLocs,
6045 SourceLocation RParenLoc) {
6046#ifndef NDEBUG
6047 if (ULE->requiresADL()) {
6048 // To do ADL, we must have found an unqualified name.
6049 assert(!ULE->getQualifier() && "qualified name with ADL");
6050
6051 // We don't perform ADL for implicit declarations of builtins.
6052 // Verify that this was correctly set up.
6053 FunctionDecl *F;
6054 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6055 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6056 F->getBuiltinID() && F->isImplicit())
6057 assert(0 && "performing ADL for builtin");
6058
6059 // We don't perform ADL in C.
6060 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6061 }
6062#endif
6063
John McCallbc077cf2010-02-08 23:07:23 +00006064 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006065
John McCall57500772009-12-16 12:17:52 +00006066 // Add the functions denoted by the callee to the set of candidate
6067 // functions, including those from argument-dependent lookup.
6068 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006069
6070 // If we found nothing, try to recover.
6071 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6072 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006073 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006074 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006075 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006076
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006077 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006078 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006079 case OR_Success: {
6080 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006081 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006082 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006083 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006084 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6085 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006086
6087 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006088 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006089 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006090 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006091 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006092 break;
6093
6094 case OR_Ambiguous:
6095 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006096 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006097 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006098 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006099
6100 case OR_Deleted:
6101 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6102 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006103 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006104 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006105 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006106 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006107 }
6108
6109 // Overload resolution failed. Destroy all of the subexpressions and
6110 // return NULL.
6111 Fn->Destroy(Context);
6112 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6113 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00006114 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006115}
6116
John McCall4c4c1df2010-01-26 03:27:55 +00006117static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006118 return Functions.size() > 1 ||
6119 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6120}
6121
Douglas Gregor084d8552009-03-13 23:49:33 +00006122/// \brief Create a unary operation that may resolve to an overloaded
6123/// operator.
6124///
6125/// \param OpLoc The location of the operator itself (e.g., '*').
6126///
6127/// \param OpcIn The UnaryOperator::Opcode that describes this
6128/// operator.
6129///
6130/// \param Functions The set of non-member functions that will be
6131/// considered by overload resolution. The caller needs to build this
6132/// set based on the context using, e.g.,
6133/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6134/// set should not contain any member functions; those will be added
6135/// by CreateOverloadedUnaryOp().
6136///
6137/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006138Sema::OwningExprResult
6139Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6140 const UnresolvedSetImpl &Fns,
6141 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006142 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6143 Expr *Input = (Expr *)input.get();
6144
6145 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6146 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6147 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6148
6149 Expr *Args[2] = { Input, 0 };
6150 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006151
Douglas Gregor084d8552009-03-13 23:49:33 +00006152 // For post-increment and post-decrement, add the implicit '0' as
6153 // the second argument, so that we know this is a post-increment or
6154 // post-decrement.
6155 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6156 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006157 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006158 SourceLocation());
6159 NumArgs = 2;
6160 }
6161
6162 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00006163 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006164 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006165 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006166 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006167 /*ADL*/ true, IsOverloaded(Fns));
6168 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00006169
Douglas Gregor084d8552009-03-13 23:49:33 +00006170 input.release();
6171 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6172 &Args[0], NumArgs,
6173 Context.DependentTy,
6174 OpLoc));
6175 }
6176
6177 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006178 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006179
6180 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006181 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006182
6183 // Add operator candidates that are member functions.
6184 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6185
John McCall4c4c1df2010-01-26 03:27:55 +00006186 // Add candidates from ADL.
6187 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006188 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006189 /*ExplicitTemplateArgs*/ 0,
6190 CandidateSet);
6191
Douglas Gregor084d8552009-03-13 23:49:33 +00006192 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006193 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006194
6195 // Perform overload resolution.
6196 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006197 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006198 case OR_Success: {
6199 // We found a built-in operator or an overloaded operator.
6200 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006201
Douglas Gregor084d8552009-03-13 23:49:33 +00006202 if (FnDecl) {
6203 // We matched an overloaded operator. Build a call to that
6204 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006205
Douglas Gregor084d8552009-03-13 23:49:33 +00006206 // Convert the arguments.
6207 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006208 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006209
John McCall16df1e52010-03-30 21:47:33 +00006210 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6211 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006212 return ExprError();
6213 } else {
6214 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006215 OwningExprResult InputInit
6216 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006217 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006218 SourceLocation(),
6219 move(input));
6220 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006221 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006222
Douglas Gregore6600372009-12-23 17:40:29 +00006223 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006224 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006225 }
6226
John McCall4fa0d5f2010-05-06 18:15:07 +00006227 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6228
Douglas Gregor084d8552009-03-13 23:49:33 +00006229 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006230 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006231
Douglas Gregor084d8552009-03-13 23:49:33 +00006232 // Build the actual expression node.
6233 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6234 SourceLocation());
6235 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006236
Douglas Gregor084d8552009-03-13 23:49:33 +00006237 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006238 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006239 ExprOwningPtr<CallExpr> TheCall(this,
6240 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006241 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006242
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006243 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6244 FnDecl))
6245 return ExprError();
6246
6247 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006248 } else {
6249 // We matched a built-in operator. Convert the arguments, then
6250 // break out so that we will build the appropriate built-in
6251 // operator node.
6252 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006253 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006254 return ExprError();
6255
6256 break;
6257 }
6258 }
6259
6260 case OR_No_Viable_Function:
6261 // No viable function; fall through to handling this as a
6262 // built-in operator, which will produce an error message for us.
6263 break;
6264
6265 case OR_Ambiguous:
6266 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6267 << UnaryOperator::getOpcodeStr(Opc)
6268 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006269 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006270 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006271 return ExprError();
6272
6273 case OR_Deleted:
6274 Diag(OpLoc, diag::err_ovl_deleted_oper)
6275 << Best->Function->isDeleted()
6276 << UnaryOperator::getOpcodeStr(Opc)
6277 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006278 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006279 return ExprError();
6280 }
6281
6282 // Either we found no viable overloaded operator or we matched a
6283 // built-in operator. In either case, fall through to trying to
6284 // build a built-in operation.
6285 input.release();
6286 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6287}
6288
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006289/// \brief Create a binary operation that may resolve to an overloaded
6290/// operator.
6291///
6292/// \param OpLoc The location of the operator itself (e.g., '+').
6293///
6294/// \param OpcIn The BinaryOperator::Opcode that describes this
6295/// operator.
6296///
6297/// \param Functions The set of non-member functions that will be
6298/// considered by overload resolution. The caller needs to build this
6299/// set based on the context using, e.g.,
6300/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6301/// set should not contain any member functions; those will be added
6302/// by CreateOverloadedBinOp().
6303///
6304/// \param LHS Left-hand argument.
6305/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006306Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006307Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006308 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006309 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006310 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006311 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006312 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006313
6314 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6315 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6316 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6317
6318 // If either side is type-dependent, create an appropriate dependent
6319 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006320 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006321 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006322 // If there are no functions to store, just build a dependent
6323 // BinaryOperator or CompoundAssignment.
6324 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6325 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6326 Context.DependentTy, OpLoc));
6327
6328 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6329 Context.DependentTy,
6330 Context.DependentTy,
6331 Context.DependentTy,
6332 OpLoc));
6333 }
John McCall4c4c1df2010-01-26 03:27:55 +00006334
6335 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006336 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006337 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006338 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006339 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006340 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006341
John McCall4c4c1df2010-01-26 03:27:55 +00006342 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006343 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006344 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006345 Context.DependentTy,
6346 OpLoc));
6347 }
6348
6349 // If this is the .* operator, which is not overloadable, just
6350 // create a built-in binary operator.
6351 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006352 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006353
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006354 // If this is the assignment operator, we only perform overload resolution
6355 // if the left-hand side is a class or enumeration type. This is actually
6356 // a hack. The standard requires that we do overload resolution between the
6357 // various built-in candidates, but as DR507 points out, this can lead to
6358 // problems. So we do it this way, which pretty much follows what GCC does.
6359 // Note that we go the traditional code path for compound assignment forms.
6360 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006361 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006362
Douglas Gregor084d8552009-03-13 23:49:33 +00006363 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006364 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006365
6366 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006367 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006368
6369 // Add operator candidates that are member functions.
6370 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6371
John McCall4c4c1df2010-01-26 03:27:55 +00006372 // Add candidates from ADL.
6373 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6374 Args, 2,
6375 /*ExplicitTemplateArgs*/ 0,
6376 CandidateSet);
6377
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006378 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006379 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006380
6381 // Perform overload resolution.
6382 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006383 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006384 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006385 // We found a built-in operator or an overloaded operator.
6386 FunctionDecl *FnDecl = Best->Function;
6387
6388 if (FnDecl) {
6389 // We matched an overloaded operator. Build a call to that
6390 // operator.
6391
6392 // Convert the arguments.
6393 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006394 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006395 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006396
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006397 OwningExprResult Arg1
6398 = PerformCopyInitialization(
6399 InitializedEntity::InitializeParameter(
6400 FnDecl->getParamDecl(0)),
6401 SourceLocation(),
6402 Owned(Args[1]));
6403 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006404 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006405
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006406 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006407 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006408 return ExprError();
6409
6410 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006411 } else {
6412 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006413 OwningExprResult Arg0
6414 = PerformCopyInitialization(
6415 InitializedEntity::InitializeParameter(
6416 FnDecl->getParamDecl(0)),
6417 SourceLocation(),
6418 Owned(Args[0]));
6419 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006420 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006421
6422 OwningExprResult Arg1
6423 = PerformCopyInitialization(
6424 InitializedEntity::InitializeParameter(
6425 FnDecl->getParamDecl(1)),
6426 SourceLocation(),
6427 Owned(Args[1]));
6428 if (Arg1.isInvalid())
6429 return ExprError();
6430 Args[0] = LHS = Arg0.takeAs<Expr>();
6431 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006432 }
6433
John McCall4fa0d5f2010-05-06 18:15:07 +00006434 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6435
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006436 // Determine the result type
6437 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006438 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006439 ResultTy = ResultTy.getNonReferenceType();
6440
6441 // Build the actual expression node.
6442 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006443 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006444 UsualUnaryConversions(FnExpr);
6445
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006446 ExprOwningPtr<CXXOperatorCallExpr>
6447 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6448 Args, 2, ResultTy,
6449 OpLoc));
6450
6451 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6452 FnDecl))
6453 return ExprError();
6454
6455 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006456 } else {
6457 // We matched a built-in operator. Convert the arguments, then
6458 // break out so that we will build the appropriate built-in
6459 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006460 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006461 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006462 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006463 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006464 return ExprError();
6465
6466 break;
6467 }
6468 }
6469
Douglas Gregor66950a32009-09-30 21:46:01 +00006470 case OR_No_Viable_Function: {
6471 // C++ [over.match.oper]p9:
6472 // If the operator is the operator , [...] and there are no
6473 // viable functions, then the operator is assumed to be the
6474 // built-in operator and interpreted according to clause 5.
6475 if (Opc == BinaryOperator::Comma)
6476 break;
6477
Sebastian Redl027de2a2009-05-21 11:50:50 +00006478 // For class as left operand for assignment or compound assigment operator
6479 // do not fall through to handling in built-in, but report that no overloaded
6480 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006481 OwningExprResult Result = ExprError();
6482 if (Args[0]->getType()->isRecordType() &&
6483 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006484 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6485 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006486 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006487 } else {
6488 // No viable function; try to create a built-in operation, which will
6489 // produce an error. Then, show the non-viable candidates.
6490 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006491 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006492 assert(Result.isInvalid() &&
6493 "C++ binary operator overloading is missing candidates!");
6494 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006495 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006496 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006497 return move(Result);
6498 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006499
6500 case OR_Ambiguous:
6501 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6502 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006503 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006504 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006505 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006506 return ExprError();
6507
6508 case OR_Deleted:
6509 Diag(OpLoc, diag::err_ovl_deleted_oper)
6510 << Best->Function->isDeleted()
6511 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006512 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006513 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006514 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006515 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006516
Douglas Gregor66950a32009-09-30 21:46:01 +00006517 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006518 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006519}
6520
Sebastian Redladba46e2009-10-29 20:17:01 +00006521Action::OwningExprResult
6522Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6523 SourceLocation RLoc,
6524 ExprArg Base, ExprArg Idx) {
6525 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6526 static_cast<Expr*>(Idx.get()) };
6527 DeclarationName OpName =
6528 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6529
6530 // If either side is type-dependent, create an appropriate dependent
6531 // expression.
6532 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6533
John McCall58cc69d2010-01-27 01:50:18 +00006534 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006535 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006536 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006537 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006538 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006539 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006540
6541 Base.release();
6542 Idx.release();
6543 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6544 Args, 2,
6545 Context.DependentTy,
6546 RLoc));
6547 }
6548
6549 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006550 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006551
6552 // Subscript can only be overloaded as a member function.
6553
6554 // Add operator candidates that are member functions.
6555 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6556
6557 // Add builtin operator candidates.
6558 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6559
6560 // Perform overload resolution.
6561 OverloadCandidateSet::iterator Best;
6562 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6563 case OR_Success: {
6564 // We found a built-in operator or an overloaded operator.
6565 FunctionDecl *FnDecl = Best->Function;
6566
6567 if (FnDecl) {
6568 // We matched an overloaded operator. Build a call to that
6569 // operator.
6570
John McCalla0296f72010-03-19 07:35:19 +00006571 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006572 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006573
Sebastian Redladba46e2009-10-29 20:17:01 +00006574 // Convert the arguments.
6575 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006576 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006577 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006578 return ExprError();
6579
Anders Carlssona68e51e2010-01-29 18:37:50 +00006580 // Convert the arguments.
6581 OwningExprResult InputInit
6582 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6583 FnDecl->getParamDecl(0)),
6584 SourceLocation(),
6585 Owned(Args[1]));
6586 if (InputInit.isInvalid())
6587 return ExprError();
6588
6589 Args[1] = InputInit.takeAs<Expr>();
6590
Sebastian Redladba46e2009-10-29 20:17:01 +00006591 // Determine the result type
6592 QualType ResultTy
6593 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6594 ResultTy = ResultTy.getNonReferenceType();
6595
6596 // Build the actual expression node.
6597 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6598 LLoc);
6599 UsualUnaryConversions(FnExpr);
6600
6601 Base.release();
6602 Idx.release();
6603 ExprOwningPtr<CXXOperatorCallExpr>
6604 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6605 FnExpr, Args, 2,
6606 ResultTy, RLoc));
6607
6608 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6609 FnDecl))
6610 return ExprError();
6611
6612 return MaybeBindToTemporary(TheCall.release());
6613 } else {
6614 // We matched a built-in operator. Convert the arguments, then
6615 // break out so that we will build the appropriate built-in
6616 // operator node.
6617 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006618 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006619 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006620 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006621 return ExprError();
6622
6623 break;
6624 }
6625 }
6626
6627 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006628 if (CandidateSet.empty())
6629 Diag(LLoc, diag::err_ovl_no_oper)
6630 << Args[0]->getType() << /*subscript*/ 0
6631 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6632 else
6633 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6634 << Args[0]->getType()
6635 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006636 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006637 "[]", LLoc);
6638 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006639 }
6640
6641 case OR_Ambiguous:
6642 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6643 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006644 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006645 "[]", LLoc);
6646 return ExprError();
6647
6648 case OR_Deleted:
6649 Diag(LLoc, diag::err_ovl_deleted_oper)
6650 << Best->Function->isDeleted() << "[]"
6651 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006652 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006653 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006654 return ExprError();
6655 }
6656
6657 // We matched a built-in operator; build it.
6658 Base.release();
6659 Idx.release();
6660 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6661 Owned(Args[1]), RLoc);
6662}
6663
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006664/// BuildCallToMemberFunction - Build a call to a member
6665/// function. MemExpr is the expression that refers to the member
6666/// function (and includes the object parameter), Args/NumArgs are the
6667/// arguments to the function call (not including the object
6668/// parameter). The caller needs to validate that the member
6669/// expression refers to a member function or an overloaded member
6670/// function.
John McCall2d74de92009-12-01 22:10:20 +00006671Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006672Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6673 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006674 unsigned NumArgs, SourceLocation *CommaLocs,
6675 SourceLocation RParenLoc) {
6676 // Dig out the member expression. This holds both the object
6677 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006678 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6679
John McCall10eae182009-11-30 22:42:35 +00006680 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006681 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006682 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006683 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006684 if (isa<MemberExpr>(NakedMemExpr)) {
6685 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006686 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006687 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006688 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006689 } else {
6690 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006691 Qualifier = UnresExpr->getQualifier();
6692
John McCall6e9f8f62009-12-03 04:06:58 +00006693 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006694
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006695 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006696 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006697
John McCall2d74de92009-12-01 22:10:20 +00006698 // FIXME: avoid copy.
6699 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6700 if (UnresExpr->hasExplicitTemplateArgs()) {
6701 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6702 TemplateArgs = &TemplateArgsBuffer;
6703 }
6704
John McCall10eae182009-11-30 22:42:35 +00006705 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6706 E = UnresExpr->decls_end(); I != E; ++I) {
6707
John McCall6e9f8f62009-12-03 04:06:58 +00006708 NamedDecl *Func = *I;
6709 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6710 if (isa<UsingShadowDecl>(Func))
6711 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6712
John McCall10eae182009-11-30 22:42:35 +00006713 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006714 // If explicit template arguments were provided, we can't call a
6715 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006716 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006717 continue;
6718
John McCalla0296f72010-03-19 07:35:19 +00006719 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006720 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006721 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006722 } else {
John McCall10eae182009-11-30 22:42:35 +00006723 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006724 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006725 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006726 CandidateSet,
6727 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006728 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006729 }
Mike Stump11289f42009-09-09 15:08:12 +00006730
John McCall10eae182009-11-30 22:42:35 +00006731 DeclarationName DeclName = UnresExpr->getMemberName();
6732
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006733 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006734 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006735 case OR_Success:
6736 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006737 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006738 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006739 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006740 break;
6741
6742 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006743 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006744 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006745 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006746 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006747 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006748 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006749
6750 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006751 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006752 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006753 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006754 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006755 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006756
6757 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006758 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006759 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006760 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006761 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006762 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006763 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006764 }
6765
John McCall16df1e52010-03-30 21:47:33 +00006766 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006767
John McCall2d74de92009-12-01 22:10:20 +00006768 // If overload resolution picked a static member, build a
6769 // non-member call based on that function.
6770 if (Method->isStatic()) {
6771 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6772 Args, NumArgs, RParenLoc);
6773 }
6774
John McCall10eae182009-11-30 22:42:35 +00006775 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006776 }
6777
6778 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006779 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006780 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006781 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006782 Method->getResultType().getNonReferenceType(),
6783 RParenLoc));
6784
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006785 // Check for a valid return type.
6786 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6787 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006788 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006789
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006790 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006791 // We only need to do this if there was actually an overload; otherwise
6792 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006793 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006794 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006795 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6796 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006797 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006798 MemExpr->setBase(ObjectArg);
6799
6800 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00006801 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00006802 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006803 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006804 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006805
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006806 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006807 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006808
John McCall2d74de92009-12-01 22:10:20 +00006809 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006810}
6811
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006812/// BuildCallToObjectOfClassType - Build a call to an object of class
6813/// type (C++ [over.call.object]), which can end up invoking an
6814/// overloaded function call operator (@c operator()) or performing a
6815/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006816Sema::ExprResult
6817Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006818 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006819 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006820 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006821 SourceLocation RParenLoc) {
6822 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006823 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006824
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006825 // C++ [over.call.object]p1:
6826 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006827 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006828 // candidate functions includes at least the function call
6829 // operators of T. The function call operators of T are obtained by
6830 // ordinary lookup of the name operator() in the context of
6831 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006832 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006833 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006834
6835 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006836 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006837 << Object->getSourceRange()))
6838 return true;
6839
John McCall27b18f82009-11-17 02:14:36 +00006840 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6841 LookupQualifiedName(R, Record->getDecl());
6842 R.suppressDiagnostics();
6843
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006844 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006845 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006846 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006847 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006848 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006849 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006850
Douglas Gregorab7897a2008-11-19 22:57:39 +00006851 // C++ [over.call.object]p2:
6852 // In addition, for each conversion function declared in T of the
6853 // form
6854 //
6855 // operator conversion-type-id () cv-qualifier;
6856 //
6857 // where cv-qualifier is the same cv-qualification as, or a
6858 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006859 // denotes the type "pointer to function of (P1,...,Pn) returning
6860 // R", or the type "reference to pointer to function of
6861 // (P1,...,Pn) returning R", or the type "reference to function
6862 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006863 // is also considered as a candidate function. Similarly,
6864 // surrogate call functions are added to the set of candidate
6865 // functions for each conversion function declared in an
6866 // accessible base class provided the function is not hidden
6867 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006868 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006869 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006870 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006871 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006872 NamedDecl *D = *I;
6873 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6874 if (isa<UsingShadowDecl>(D))
6875 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6876
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006877 // Skip over templated conversion functions; they aren't
6878 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006879 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006880 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006881
John McCall6e9f8f62009-12-03 04:06:58 +00006882 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006883
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006884 // Strip the reference type (if any) and then the pointer type (if
6885 // any) to get down to what might be a function type.
6886 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6887 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6888 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006889
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006890 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006891 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006892 Object->getType(), Args, NumArgs,
6893 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006894 }
Mike Stump11289f42009-09-09 15:08:12 +00006895
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006896 // Perform overload resolution.
6897 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006898 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006899 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006900 // Overload resolution succeeded; we'll build the appropriate call
6901 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006902 break;
6903
6904 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006905 if (CandidateSet.empty())
6906 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6907 << Object->getType() << /*call*/ 1
6908 << Object->getSourceRange();
6909 else
6910 Diag(Object->getSourceRange().getBegin(),
6911 diag::err_ovl_no_viable_object_call)
6912 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006913 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006914 break;
6915
6916 case OR_Ambiguous:
6917 Diag(Object->getSourceRange().getBegin(),
6918 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006919 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006920 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006921 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006922
6923 case OR_Deleted:
6924 Diag(Object->getSourceRange().getBegin(),
6925 diag::err_ovl_deleted_object_call)
6926 << Best->Function->isDeleted()
6927 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006928 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006929 break;
Mike Stump11289f42009-09-09 15:08:12 +00006930 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006931
Douglas Gregorab7897a2008-11-19 22:57:39 +00006932 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006933 // We had an error; delete all of the subexpressions and return
6934 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006935 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006936 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006937 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006938 return true;
6939 }
6940
Douglas Gregorab7897a2008-11-19 22:57:39 +00006941 if (Best->Function == 0) {
6942 // Since there is no function declaration, this is one of the
6943 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006944 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006945 = cast<CXXConversionDecl>(
6946 Best->Conversions[0].UserDefined.ConversionFunction);
6947
John McCalla0296f72010-03-19 07:35:19 +00006948 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006949 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006950
Douglas Gregorab7897a2008-11-19 22:57:39 +00006951 // We selected one of the surrogate functions that converts the
6952 // object parameter to a function pointer. Perform the conversion
6953 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006954
6955 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006956 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006957 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6958 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006959
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006960 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006961 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006962 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006963 }
6964
John McCalla0296f72010-03-19 07:35:19 +00006965 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006966 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006967
Douglas Gregorab7897a2008-11-19 22:57:39 +00006968 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6969 // that calls this method, using Object for the implicit object
6970 // parameter and passing along the remaining arguments.
6971 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006972 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006973
6974 unsigned NumArgsInProto = Proto->getNumArgs();
6975 unsigned NumArgsToCheck = NumArgs;
6976
6977 // Build the full argument list for the method call (the
6978 // implicit object parameter is placed at the beginning of the
6979 // list).
6980 Expr **MethodArgs;
6981 if (NumArgs < NumArgsInProto) {
6982 NumArgsToCheck = NumArgsInProto;
6983 MethodArgs = new Expr*[NumArgsInProto + 1];
6984 } else {
6985 MethodArgs = new Expr*[NumArgs + 1];
6986 }
6987 MethodArgs[0] = Object;
6988 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6989 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006990
6991 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006992 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006993 UsualUnaryConversions(NewFn);
6994
6995 // Once we've built TheCall, all of the expressions are properly
6996 // owned.
6997 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006998 ExprOwningPtr<CXXOperatorCallExpr>
6999 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007000 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007001 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007002 delete [] MethodArgs;
7003
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007004 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7005 Method))
7006 return true;
7007
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007008 // We may have default arguments. If so, we need to allocate more
7009 // slots in the call for them.
7010 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007011 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007012 else if (NumArgs > NumArgsInProto)
7013 NumArgsToCheck = NumArgsInProto;
7014
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007015 bool IsError = false;
7016
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007017 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007018 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007019 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007020 TheCall->setArg(0, Object);
7021
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007022
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007023 // Check the argument types.
7024 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007025 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007026 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007027 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007028
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007029 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007030
7031 OwningExprResult InputInit
7032 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7033 Method->getParamDecl(i)),
7034 SourceLocation(), Owned(Arg));
7035
7036 IsError |= InputInit.isInvalid();
7037 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007038 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007039 OwningExprResult DefArg
7040 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7041 if (DefArg.isInvalid()) {
7042 IsError = true;
7043 break;
7044 }
7045
7046 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007047 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007048
7049 TheCall->setArg(i + 1, Arg);
7050 }
7051
7052 // If this is a variadic call, handle args passed through "...".
7053 if (Proto->isVariadic()) {
7054 // Promote the arguments (C99 6.5.2.2p7).
7055 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7056 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007057 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007058 TheCall->setArg(i + 1, Arg);
7059 }
7060 }
7061
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007062 if (IsError) return true;
7063
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007064 if (CheckFunctionCall(Method, TheCall.get()))
7065 return true;
7066
Douglas Gregore5e775b2010-04-13 15:50:39 +00007067 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007068}
7069
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007070/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007071/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007072/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007073Sema::OwningExprResult
7074Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7075 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007076 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007077
John McCallbc077cf2010-02-08 23:07:23 +00007078 SourceLocation Loc = Base->getExprLoc();
7079
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007080 // C++ [over.ref]p1:
7081 //
7082 // [...] An expression x->m is interpreted as (x.operator->())->m
7083 // for a class object x of type T if T::operator->() exists and if
7084 // the operator is selected as the best match function by the
7085 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007086 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007087 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007088 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007089
John McCallbc077cf2010-02-08 23:07:23 +00007090 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007091 PDiag(diag::err_typecheck_incomplete_tag)
7092 << Base->getSourceRange()))
7093 return ExprError();
7094
John McCall27b18f82009-11-17 02:14:36 +00007095 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7096 LookupQualifiedName(R, BaseRecord->getDecl());
7097 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007098
7099 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007100 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007101 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007102 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007103 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007104
7105 // Perform overload resolution.
7106 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007107 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007108 case OR_Success:
7109 // Overload resolution succeeded; we'll build the call below.
7110 break;
7111
7112 case OR_No_Viable_Function:
7113 if (CandidateSet.empty())
7114 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007115 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007116 else
7117 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007118 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007119 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007120 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007121
7122 case OR_Ambiguous:
7123 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007124 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007125 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007126 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007127
7128 case OR_Deleted:
7129 Diag(OpLoc, diag::err_ovl_deleted_oper)
7130 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007131 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007132 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007133 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007134 }
7135
John McCalla0296f72010-03-19 07:35:19 +00007136 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007137 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007138
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007139 // Convert the object parameter.
7140 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007141 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7142 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007143 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007144
7145 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007146 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007147
7148 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007149 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7150 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007151 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007152
7153 QualType ResultTy = Method->getResultType().getNonReferenceType();
7154 ExprOwningPtr<CXXOperatorCallExpr>
7155 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7156 &Base, 1, ResultTy, OpLoc));
7157
7158 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7159 Method))
7160 return ExprError();
7161 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007162}
7163
Douglas Gregorcd695e52008-11-10 20:40:00 +00007164/// FixOverloadedFunctionReference - E is an expression that refers to
7165/// a C++ overloaded function (possibly with some parentheses and
7166/// perhaps a '&' around it). We have resolved the overloaded function
7167/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007168/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007169Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007170 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007171 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007172 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7173 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007174 if (SubExpr == PE->getSubExpr())
7175 return PE->Retain();
7176
7177 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7178 }
7179
7180 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007181 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7182 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007183 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007184 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007185 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007186 if (SubExpr == ICE->getSubExpr())
7187 return ICE->Retain();
7188
7189 return new (Context) ImplicitCastExpr(ICE->getType(),
7190 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007191 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007192 ICE->isLvalueCast());
7193 }
7194
7195 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007196 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007197 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007198 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7199 if (Method->isStatic()) {
7200 // Do nothing: static member functions aren't any different
7201 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007202 } else {
John McCalle66edc12009-11-24 19:00:30 +00007203 // Fix the sub expression, which really has to be an
7204 // UnresolvedLookupExpr holding an overloaded member function
7205 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007206 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7207 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007208 if (SubExpr == UnOp->getSubExpr())
7209 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007210
John McCalld14a8642009-11-21 08:51:07 +00007211 assert(isa<DeclRefExpr>(SubExpr)
7212 && "fixed to something other than a decl ref");
7213 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7214 && "fixed to a member ref with no nested name qualifier");
7215
7216 // We have taken the address of a pointer to member
7217 // function. Perform the computation here so that we get the
7218 // appropriate pointer to member type.
7219 QualType ClassType
7220 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7221 QualType MemPtrType
7222 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7223
7224 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7225 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007226 }
7227 }
John McCall16df1e52010-03-30 21:47:33 +00007228 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7229 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007230 if (SubExpr == UnOp->getSubExpr())
7231 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007232
Douglas Gregor51c538b2009-11-20 19:42:02 +00007233 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7234 Context.getPointerType(SubExpr->getType()),
7235 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007236 }
John McCalld14a8642009-11-21 08:51:07 +00007237
7238 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007239 // FIXME: avoid copy.
7240 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007241 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007242 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7243 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007244 }
7245
John McCalld14a8642009-11-21 08:51:07 +00007246 return DeclRefExpr::Create(Context,
7247 ULE->getQualifier(),
7248 ULE->getQualifierRange(),
7249 Fn,
7250 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007251 Fn->getType(),
7252 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007253 }
7254
John McCall10eae182009-11-30 22:42:35 +00007255 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007256 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007257 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7258 if (MemExpr->hasExplicitTemplateArgs()) {
7259 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7260 TemplateArgs = &TemplateArgsBuffer;
7261 }
John McCall6b51f282009-11-23 01:53:49 +00007262
John McCall2d74de92009-12-01 22:10:20 +00007263 Expr *Base;
7264
7265 // If we're filling in
7266 if (MemExpr->isImplicitAccess()) {
7267 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7268 return DeclRefExpr::Create(Context,
7269 MemExpr->getQualifier(),
7270 MemExpr->getQualifierRange(),
7271 Fn,
7272 MemExpr->getMemberLoc(),
7273 Fn->getType(),
7274 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007275 } else {
7276 SourceLocation Loc = MemExpr->getMemberLoc();
7277 if (MemExpr->getQualifier())
7278 Loc = MemExpr->getQualifierRange().getBegin();
7279 Base = new (Context) CXXThisExpr(Loc,
7280 MemExpr->getBaseType(),
7281 /*isImplicit=*/true);
7282 }
John McCall2d74de92009-12-01 22:10:20 +00007283 } else
7284 Base = MemExpr->getBase()->Retain();
7285
7286 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007287 MemExpr->isArrow(),
7288 MemExpr->getQualifier(),
7289 MemExpr->getQualifierRange(),
7290 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007291 Found,
John McCall6b51f282009-11-23 01:53:49 +00007292 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007293 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007294 Fn->getType());
7295 }
7296
Douglas Gregor51c538b2009-11-20 19:42:02 +00007297 assert(false && "Invalid reference to overloaded function");
7298 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007299}
7300
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007301Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007302 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007303 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007304 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007305}
7306
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007307} // end namespace clang