blob: 517574b5955d45fafb239fc0dfb505f0ae0540ee [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:
344 delete static_cast<DFIParamWithArguments*>(Data);
345 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 Gregor1d72edd2010-05-08 19:15:54 +0000462 //
463 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
464 if (C->FailureKind == ovl_fail_bad_deduction)
465 C->DeductionFailure.Destroy();
466 }
467
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000468 inherited::clear();
469 Functions.clear();
470}
471
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000473// overload of the declarations in Old. This routine returns false if
474// New and Old cannot be overloaded, e.g., if New has the same
475// signature as some function in Old (C++ 1.3.10) or if the Old
476// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000477// it does return false, MatchedDecl will point to the decl that New
478// cannot be overloaded with. This decl may be a UsingShadowDecl on
479// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480//
481// Example: Given the following input:
482//
483// void f(int, float); // #1
484// void f(int, int); // #2
485// int f(int, int); // #3
486//
487// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000488// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489//
John McCall3d988d92009-12-02 08:47:38 +0000490// When we process #2, Old contains only the FunctionDecl for #1. By
491// comparing the parameter types, we see that #1 and #2 are overloaded
492// (since they have different signatures), so this routine returns
493// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494//
John McCall3d988d92009-12-02 08:47:38 +0000495// When we process #3, Old is an overload set containing #1 and #2. We
496// compare the signatures of #3 to #1 (they're overloaded, so we do
497// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
498// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499// signature), IsOverload returns false and MatchedDecl will be set to
500// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000501Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000502Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
503 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000504 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000505 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000506 NamedDecl *OldD = (*I)->getUnderlyingDecl();
507 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000508 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000509 Match = *I;
510 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511 }
John McCall3d988d92009-12-02 08:47:38 +0000512 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000513 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000514 Match = *I;
515 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000516 }
John McCall84d87672009-12-10 09:41:52 +0000517 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
518 // We can overload with these, which can show up when doing
519 // redeclaration checks for UsingDecls.
520 assert(Old.getLookupKind() == LookupUsingDeclName);
521 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
522 // Optimistically assume that an unresolved using decl will
523 // overload; if it doesn't, we'll have to diagnose during
524 // template instantiation.
525 } else {
John McCall1f82f242009-11-18 22:49:29 +0000526 // (C++ 13p1):
527 // Only function declarations can be overloaded; object and type
528 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000529 Match = *I;
530 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000531 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532 }
John McCall1f82f242009-11-18 22:49:29 +0000533
John McCalldaa3d6b2009-12-09 03:35:25 +0000534 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000535}
536
537bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
538 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
539 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
540
541 // C++ [temp.fct]p2:
542 // A function template can be overloaded with other function templates
543 // and with normal (non-template) functions.
544 if ((OldTemplate == 0) != (NewTemplate == 0))
545 return true;
546
547 // Is the function New an overload of the function Old?
548 QualType OldQType = Context.getCanonicalType(Old->getType());
549 QualType NewQType = Context.getCanonicalType(New->getType());
550
551 // Compare the signatures (C++ 1.3.10) of the two functions to
552 // determine whether they are overloads. If we find any mismatch
553 // in the signature, they are overloads.
554
555 // If either of these functions is a K&R-style function (no
556 // prototype), then we consider them to have matching signatures.
557 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
558 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
559 return false;
560
561 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
562 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
563
564 // The signature of a function includes the types of its
565 // parameters (C++ 1.3.10), which includes the presence or absence
566 // of the ellipsis; see C++ DR 357).
567 if (OldQType != NewQType &&
568 (OldType->getNumArgs() != NewType->getNumArgs() ||
569 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000570 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000571 return true;
572
573 // C++ [temp.over.link]p4:
574 // The signature of a function template consists of its function
575 // signature, its return type and its template parameter list. The names
576 // of the template parameters are significant only for establishing the
577 // relationship between the template parameters and the rest of the
578 // signature.
579 //
580 // We check the return type and template parameter lists for function
581 // templates first; the remaining checks follow.
582 if (NewTemplate &&
583 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
584 OldTemplate->getTemplateParameters(),
585 false, TPL_TemplateMatch) ||
586 OldType->getResultType() != NewType->getResultType()))
587 return true;
588
589 // If the function is a class member, its signature includes the
590 // cv-qualifiers (if any) on the function itself.
591 //
592 // As part of this, also check whether one of the member functions
593 // is static, in which case they are not overloads (C++
594 // 13.1p2). While not part of the definition of the signature,
595 // this check is important to determine whether these functions
596 // can be overloaded.
597 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
598 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
599 if (OldMethod && NewMethod &&
600 !OldMethod->isStatic() && !NewMethod->isStatic() &&
601 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
602 return true;
603
604 // The signatures match; this is not an overload.
605 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000606}
607
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000608/// TryImplicitConversion - Attempt to perform an implicit conversion
609/// from the given expression (Expr) to the given type (ToType). This
610/// function returns an implicit conversion sequence that can be used
611/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612///
613/// void f(float f);
614/// void g(int i) { f(i); }
615///
616/// this routine would produce an implicit conversion sequence to
617/// describe the initialization of f from i, which will be a standard
618/// conversion sequence containing an lvalue-to-rvalue conversion (C++
619/// 4.1) followed by a floating-integral conversion (C++ 4.9).
620//
621/// Note that this routine only determines how the conversion can be
622/// performed; it does not actually perform the conversion. As such,
623/// it will not produce any diagnostics if no conversion is available,
624/// but will instead return an implicit conversion sequence of kind
625/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000626///
627/// If @p SuppressUserConversions, then user-defined conversions are
628/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000629/// If @p AllowExplicit, then explicit user-defined conversions are
630/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000631ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000632Sema::TryImplicitConversion(Expr* From, QualType ToType,
633 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000634 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000635 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000636 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000637 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000638 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000639 return ICS;
640 }
641
642 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000643 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000644 return ICS;
645 }
646
Douglas Gregor5ab11652010-04-17 22:01:05 +0000647 if (SuppressUserConversions) {
648 // C++ [over.ics.user]p4:
649 // A conversion of an expression of class type to the same class
650 // type is given Exact Match rank, and a conversion of an
651 // expression of class type to a base class of that type is
652 // given Conversion rank, in spite of the fact that a copy/move
653 // constructor (i.e., a user-defined conversion function) is
654 // called for those cases.
655 QualType FromType = From->getType();
656 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
657 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
658 IsDerivedFrom(FromType, ToType))) {
659 // We're not in the case above, so there is no conversion that
660 // we can perform.
661 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
662 return ICS;
663 }
664
665 ICS.setStandard();
666 ICS.Standard.setAsIdentityConversion();
667 ICS.Standard.setFromType(FromType);
668 ICS.Standard.setAllToTypes(ToType);
669
670 // We don't actually check at this point whether there is a valid
671 // copy/move constructor, since overloading just assumes that it
672 // exists. When we actually perform initialization, we'll find the
673 // appropriate constructor to copy the returned object, if needed.
674 ICS.Standard.CopyConstructor = 0;
675
676 // Determine whether this is considered a derived-to-base conversion.
677 if (!Context.hasSameUnqualifiedType(FromType, ToType))
678 ICS.Standard.Second = ICK_Derived_To_Base;
679
680 return ICS;
681 }
682
683 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000684 OverloadCandidateSet Conversions(From->getExprLoc());
685 OverloadingResult UserDefResult
686 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000687 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000688
689 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000690 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000691 // C++ [over.ics.user]p4:
692 // A conversion of an expression of class type to the same class
693 // type is given Exact Match rank, and a conversion of an
694 // expression of class type to a base class of that type is
695 // given Conversion rank, in spite of the fact that a copy
696 // constructor (i.e., a user-defined conversion function) is
697 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000698 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000699 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000700 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000701 = Context.getCanonicalType(From->getType().getUnqualifiedType());
702 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000703 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000704 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000705 // Turn this into a "standard" conversion sequence, so that it
706 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000707 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000708 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000709 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000710 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000711 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000712 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000713 ICS.Standard.Second = ICK_Derived_To_Base;
714 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000715 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000716
717 // C++ [over.best.ics]p4:
718 // However, when considering the argument of a user-defined
719 // conversion function that is a candidate by 13.3.1.3 when
720 // invoked for the copying of the temporary in the second step
721 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
722 // 13.3.1.6 in all cases, only standard conversion sequences and
723 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000724 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000725 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000726 }
John McCalle8c8cd22010-01-13 22:30:33 +0000727 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000728 ICS.setAmbiguous();
729 ICS.Ambiguous.setFromType(From->getType());
730 ICS.Ambiguous.setToType(ToType);
731 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
732 Cand != Conversions.end(); ++Cand)
733 if (Cand->Viable)
734 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000735 } else {
John McCall65eb8792010-02-25 01:37:24 +0000736 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000737 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000738
739 return ICS;
740}
741
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000742/// PerformImplicitConversion - Perform an implicit conversion of the
743/// expression From to the type ToType. Returns true if there was an
744/// error, false otherwise. The expression From is replaced with the
745/// converted expression. Flavor is the kind of conversion we're
746/// performing, used in the error message. If @p AllowExplicit,
747/// explicit user-defined conversions are permitted.
748bool
749Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
750 AssignmentAction Action, bool AllowExplicit) {
751 ImplicitConversionSequence ICS;
752 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
753}
754
755bool
756Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
757 AssignmentAction Action, bool AllowExplicit,
758 ImplicitConversionSequence& ICS) {
759 ICS = TryImplicitConversion(From, ToType,
760 /*SuppressUserConversions=*/false,
761 AllowExplicit,
762 /*InOverloadResolution=*/false);
763 return PerformImplicitConversion(From, ToType, ICS, Action);
764}
765
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000766/// \brief Determine whether the conversion from FromType to ToType is a valid
767/// conversion that strips "noreturn" off the nested function type.
768static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
769 QualType ToType, QualType &ResultTy) {
770 if (Context.hasSameUnqualifiedType(FromType, ToType))
771 return false;
772
773 // Strip the noreturn off the type we're converting from; noreturn can
774 // safely be removed.
775 FromType = Context.getNoReturnType(FromType, false);
776 if (!Context.hasSameUnqualifiedType(FromType, ToType))
777 return false;
778
779 ResultTy = FromType;
780 return true;
781}
782
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000783/// IsStandardConversion - Determines whether there is a standard
784/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
785/// expression From to the type ToType. Standard conversion sequences
786/// only consider non-class types; for conversions that involve class
787/// types, use TryImplicitConversion. If a conversion exists, SCS will
788/// contain the standard conversion sequence required to perform this
789/// conversion and this routine will return true. Otherwise, this
790/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000791bool
792Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000793 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000794 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000795 QualType FromType = From->getType();
796
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000797 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000798 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000799 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000800 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000801 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000802 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000804 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000805 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000806 if (FromType->isRecordType() || ToType->isRecordType()) {
807 if (getLangOptions().CPlusPlus)
808 return false;
809
Mike Stump11289f42009-09-09 15:08:12 +0000810 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000811 }
812
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000813 // The first conversion can be an lvalue-to-rvalue conversion,
814 // array-to-pointer conversion, or function-to-pointer conversion
815 // (C++ 4p1).
816
Douglas Gregor980fb162010-04-29 18:24:40 +0000817 if (FromType == Context.OverloadTy) {
818 DeclAccessPair AccessPair;
819 if (FunctionDecl *Fn
820 = ResolveAddressOfOverloadedFunction(From, ToType, false,
821 AccessPair)) {
822 // We were able to resolve the address of the overloaded function,
823 // so we can convert to the type of that function.
824 FromType = Fn->getType();
825 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
826 if (!Method->isStatic()) {
827 Type *ClassType
828 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
829 FromType = Context.getMemberPointerType(FromType, ClassType);
830 }
831 }
832
833 // If the "from" expression takes the address of the overloaded
834 // function, update the type of the resulting expression accordingly.
835 if (FromType->getAs<FunctionType>())
836 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
837 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
838 FromType = Context.getPointerType(FromType);
839
840 // Check that we've computed the proper type after overload resolution.
841 assert(Context.hasSameType(FromType,
842 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
843 } else {
844 return false;
845 }
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000848 // An lvalue (3.10) of a non-function, non-array type T can be
849 // converted to an rvalue.
850 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000851 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000852 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000853 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000854 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000855
856 // If T is a non-class type, the type of the rvalue is the
857 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000858 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
859 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000860 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000861 } else if (FromType->isArrayType()) {
862 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000863 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000864
865 // An lvalue or rvalue of type "array of N T" or "array of unknown
866 // bound of T" can be converted to an rvalue of type "pointer to
867 // T" (C++ 4.2p1).
868 FromType = Context.getArrayDecayedType(FromType);
869
870 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
871 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000872 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000873
874 // For the purpose of ranking in overload resolution
875 // (13.3.3.1.1), this conversion is considered an
876 // array-to-pointer conversion followed by a qualification
877 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000878 SCS.Second = ICK_Identity;
879 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000880 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000881 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000882 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000883 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
884 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000885 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886
887 // An lvalue of function type T can be converted to an rvalue of
888 // type "pointer to T." The result is a pointer to the
889 // function. (C++ 4.3p1).
890 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000891 } else {
892 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000893 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000894 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000895 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896
897 // The second conversion can be an integral promotion, floating
898 // point promotion, integral conversion, floating point conversion,
899 // floating-integral conversion, pointer conversion,
900 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000901 // For overloading in C, this can also be a "compatible-type"
902 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000903 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000904 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000905 // The unqualified versions of the types are the same: there's no
906 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000907 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000908 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000909 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000910 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000911 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000912 } else if (IsFloatingPointPromotion(FromType, ToType)) {
913 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000914 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000915 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000916 } else if (IsComplexPromotion(FromType, ToType)) {
917 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000918 SCS.Second = ICK_Complex_Promotion;
919 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000920 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000921 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000922 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000923 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000924 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000925 } else if (FromType->isComplexType() && ToType->isComplexType()) {
926 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000927 SCS.Second = ICK_Complex_Conversion;
928 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000929 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
930 (ToType->isComplexType() && FromType->isArithmeticType())) {
931 // Complex-real conversions (C99 6.3.1.7)
932 SCS.Second = ICK_Complex_Real;
933 FromType = ToType.getUnqualifiedType();
934 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
935 // Floating point conversions (C++ 4.8).
936 SCS.Second = ICK_Floating_Conversion;
937 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000938 } else if ((FromType->isFloatingType() &&
939 ToType->isIntegralType() && (!ToType->isBooleanType() &&
940 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000941 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000942 ToType->isFloatingType())) {
943 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000944 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000945 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000946 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
947 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000948 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000949 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000950 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000951 } else if (IsMemberPointerConversion(From, FromType, ToType,
952 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000953 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000954 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000955 } else if (ToType->isBooleanType() &&
956 (FromType->isArithmeticType() ||
957 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000958 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000959 FromType->isBlockPointerType() ||
960 FromType->isMemberPointerType() ||
961 FromType->isNullPtrType())) {
962 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000963 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000964 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000965 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000966 Context.typesAreCompatible(ToType, FromType)) {
967 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000968 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000969 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
970 // Treat a conversion that strips "noreturn" as an identity conversion.
971 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000972 } else {
973 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000974 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000975 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000976 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000977
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000978 QualType CanonFrom;
979 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000980 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000981 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000982 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000983 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000984 CanonFrom = Context.getCanonicalType(FromType);
985 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000986 } else {
987 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000988 SCS.Third = ICK_Identity;
989
Mike Stump11289f42009-09-09 15:08:12 +0000990 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000991 // [...] Any difference in top-level cv-qualification is
992 // subsumed by the initialization itself and does not constitute
993 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000994 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000995 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000996 if (CanonFrom.getLocalUnqualifiedType()
997 == CanonTo.getLocalUnqualifiedType() &&
998 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000999 FromType = ToType;
1000 CanonFrom = CanonTo;
1001 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001002 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001003 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001004
1005 // If we have not converted the argument type to the parameter type,
1006 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001007 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001008 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001009
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001010 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001011}
1012
1013/// IsIntegralPromotion - Determines whether the conversion from the
1014/// expression From (whose potentially-adjusted type is FromType) to
1015/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1016/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001017bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001018 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001019 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001020 if (!To) {
1021 return false;
1022 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001023
1024 // An rvalue of type char, signed char, unsigned char, short int, or
1025 // unsigned short int can be converted to an rvalue of type int if
1026 // int can represent all the values of the source type; otherwise,
1027 // the source rvalue can be converted to an rvalue of type unsigned
1028 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001029 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1030 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001031 if (// We can promote any signed, promotable integer type to an int
1032 (FromType->isSignedIntegerType() ||
1033 // We can promote any unsigned integer type whose size is
1034 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001035 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001036 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001037 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001038 }
1039
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001040 return To->getKind() == BuiltinType::UInt;
1041 }
1042
1043 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1044 // can be converted to an rvalue of the first of the following types
1045 // that can represent all the values of its underlying type: int,
1046 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001047
1048 // We pre-calculate the promotion type for enum types.
1049 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1050 if (ToType->isIntegerType())
1051 return Context.hasSameUnqualifiedType(ToType,
1052 FromEnumType->getDecl()->getPromotionType());
1053
1054 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001055 // Determine whether the type we're converting from is signed or
1056 // unsigned.
1057 bool FromIsSigned;
1058 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001059
1060 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1061 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062
1063 // The types we'll try to promote to, in the appropriate
1064 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001065 QualType PromoteTypes[6] = {
1066 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001067 Context.LongTy, Context.UnsignedLongTy ,
1068 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001069 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001070 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1072 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001073 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001074 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1075 // We found the type that we can promote to. If this is the
1076 // type we wanted, we have a promotion. Otherwise, no
1077 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001078 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001079 }
1080 }
1081 }
1082
1083 // An rvalue for an integral bit-field (9.6) can be converted to an
1084 // rvalue of type int if int can represent all the values of the
1085 // bit-field; otherwise, it can be converted to unsigned int if
1086 // unsigned int can represent all the values of the bit-field. If
1087 // the bit-field is larger yet, no integral promotion applies to
1088 // it. If the bit-field has an enumerated type, it is treated as any
1089 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001090 // FIXME: We should delay checking of bit-fields until we actually perform the
1091 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001092 using llvm::APSInt;
1093 if (From)
1094 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001095 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +00001096 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
1097 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1098 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1099 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001100
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001101 // Are we promoting to an int from a bitfield that fits in an int?
1102 if (BitWidth < ToSize ||
1103 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1104 return To->getKind() == BuiltinType::Int;
1105 }
Mike Stump11289f42009-09-09 15:08:12 +00001106
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001107 // Are we promoting to an unsigned int from an unsigned bitfield
1108 // that fits into an unsigned int?
1109 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1110 return To->getKind() == BuiltinType::UInt;
1111 }
Mike Stump11289f42009-09-09 15:08:12 +00001112
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001113 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001114 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001115 }
Mike Stump11289f42009-09-09 15:08:12 +00001116
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001117 // An rvalue of type bool can be converted to an rvalue of type int,
1118 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001119 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001120 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001121 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122
1123 return false;
1124}
1125
1126/// IsFloatingPointPromotion - Determines whether the conversion from
1127/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1128/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001129bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130 /// An rvalue of type float can be converted to an rvalue of type
1131 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001132 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1133 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001134 if (FromBuiltin->getKind() == BuiltinType::Float &&
1135 ToBuiltin->getKind() == BuiltinType::Double)
1136 return true;
1137
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001138 // C99 6.3.1.5p1:
1139 // When a float is promoted to double or long double, or a
1140 // double is promoted to long double [...].
1141 if (!getLangOptions().CPlusPlus &&
1142 (FromBuiltin->getKind() == BuiltinType::Float ||
1143 FromBuiltin->getKind() == BuiltinType::Double) &&
1144 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1145 return true;
1146 }
1147
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001148 return false;
1149}
1150
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001151/// \brief Determine if a conversion is a complex promotion.
1152///
1153/// A complex promotion is defined as a complex -> complex conversion
1154/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001155/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001156bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001157 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001158 if (!FromComplex)
1159 return false;
1160
John McCall9dd450b2009-09-21 23:43:11 +00001161 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001162 if (!ToComplex)
1163 return false;
1164
1165 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001166 ToComplex->getElementType()) ||
1167 IsIntegralPromotion(0, FromComplex->getElementType(),
1168 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001169}
1170
Douglas Gregor237f96c2008-11-26 23:31:11 +00001171/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1172/// the pointer type FromPtr to a pointer to type ToPointee, with the
1173/// same type qualifiers as FromPtr has on its pointee type. ToType,
1174/// if non-empty, will be a pointer to ToType that may or may not have
1175/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001176static QualType
1177BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001178 QualType ToPointee, QualType ToType,
1179 ASTContext &Context) {
1180 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1181 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001182 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001183
1184 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001185 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001186 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001187 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +00001188 return ToType;
1189
1190 // Build a pointer to ToPointee. It has the right qualifiers
1191 // already.
1192 return Context.getPointerType(ToPointee);
1193 }
1194
1195 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001196 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001197 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1198 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001199}
1200
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001201/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1202/// the FromType, which is an objective-c pointer, to ToType, which may or may
1203/// not have the right set of qualifiers.
1204static QualType
1205BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1206 QualType ToType,
1207 ASTContext &Context) {
1208 QualType CanonFromType = Context.getCanonicalType(FromType);
1209 QualType CanonToType = Context.getCanonicalType(ToType);
1210 Qualifiers Quals = CanonFromType.getQualifiers();
1211
1212 // Exact qualifier match -> return the pointer type we're converting to.
1213 if (CanonToType.getLocalQualifiers() == Quals)
1214 return ToType;
1215
1216 // Just build a canonical type that has the right qualifiers.
1217 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1218}
1219
Mike Stump11289f42009-09-09 15:08:12 +00001220static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001221 bool InOverloadResolution,
1222 ASTContext &Context) {
1223 // Handle value-dependent integral null pointer constants correctly.
1224 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1225 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1226 Expr->getType()->isIntegralType())
1227 return !InOverloadResolution;
1228
Douglas Gregor56751b52009-09-25 04:25:58 +00001229 return Expr->isNullPointerConstant(Context,
1230 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1231 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001232}
Mike Stump11289f42009-09-09 15:08:12 +00001233
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001234/// IsPointerConversion - Determines whether the conversion of the
1235/// expression From, which has the (possibly adjusted) type FromType,
1236/// can be converted to the type ToType via a pointer conversion (C++
1237/// 4.10). If so, returns true and places the converted type (that
1238/// might differ from ToType in its cv-qualifiers at some level) into
1239/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001240///
Douglas Gregora29dc052008-11-27 01:19:21 +00001241/// This routine also supports conversions to and from block pointers
1242/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1243/// pointers to interfaces. FIXME: Once we've determined the
1244/// appropriate overloading rules for Objective-C, we may want to
1245/// split the Objective-C checks into a different routine; however,
1246/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001247/// conversions, so for now they live here. IncompatibleObjC will be
1248/// set if the conversion is an allowed Objective-C conversion that
1249/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001250bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001251 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001252 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001253 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001254 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001255 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1256 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001257
Mike Stump11289f42009-09-09 15:08:12 +00001258 // Conversion from a null pointer constant to any Objective-C pointer type.
1259 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001260 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001261 ConvertedType = ToType;
1262 return true;
1263 }
1264
Douglas Gregor231d1c62008-11-27 00:15:41 +00001265 // Blocks: Block pointers can be converted to void*.
1266 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001267 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001268 ConvertedType = ToType;
1269 return true;
1270 }
1271 // Blocks: A null pointer constant can be converted to a block
1272 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001273 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001274 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001275 ConvertedType = ToType;
1276 return true;
1277 }
1278
Sebastian Redl576fd422009-05-10 18:38:11 +00001279 // If the left-hand-side is nullptr_t, the right side can be a null
1280 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001281 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001282 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001283 ConvertedType = ToType;
1284 return true;
1285 }
1286
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001287 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001288 if (!ToTypePtr)
1289 return false;
1290
1291 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001292 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001293 ConvertedType = ToType;
1294 return true;
1295 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001296
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001297 // Beyond this point, both types need to be pointers
1298 // , including objective-c pointers.
1299 QualType ToPointeeType = ToTypePtr->getPointeeType();
1300 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1301 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1302 ToType, Context);
1303 return true;
1304
1305 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001306 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001307 if (!FromTypePtr)
1308 return false;
1309
1310 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001311
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001312 // An rvalue of type "pointer to cv T," where T is an object type,
1313 // can be converted to an rvalue of type "pointer to cv void" (C++
1314 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001315 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001316 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001317 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001318 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001319 return true;
1320 }
1321
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001322 // When we're overloading in C, we allow a special kind of pointer
1323 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001324 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001325 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001326 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001327 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001328 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001329 return true;
1330 }
1331
Douglas Gregor5c407d92008-10-23 00:40:37 +00001332 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001333 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001334 // An rvalue of type "pointer to cv D," where D is a class type,
1335 // can be converted to an rvalue of type "pointer to cv B," where
1336 // B is a base class (clause 10) of D. If B is an inaccessible
1337 // (clause 11) or ambiguous (10.2) base class of D, a program that
1338 // necessitates this conversion is ill-formed. The result of the
1339 // conversion is a pointer to the base class sub-object of the
1340 // derived class object. The null pointer value is converted to
1341 // the null pointer value of the destination type.
1342 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001343 // Note that we do not check for ambiguity or inaccessibility
1344 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001345 if (getLangOptions().CPlusPlus &&
1346 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001347 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001348 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001349 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001350 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001351 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001352 ToType, Context);
1353 return true;
1354 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001355
Douglas Gregora119f102008-12-19 19:13:09 +00001356 return false;
1357}
1358
1359/// isObjCPointerConversion - Determines whether this is an
1360/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1361/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001362bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001363 QualType& ConvertedType,
1364 bool &IncompatibleObjC) {
1365 if (!getLangOptions().ObjC1)
1366 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001367
Steve Naroff7cae42b2009-07-10 23:34:53 +00001368 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001369 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001370 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001371 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001372
Steve Naroff7cae42b2009-07-10 23:34:53 +00001373 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001374 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001375 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001376 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001377 ConvertedType = ToType;
1378 return true;
1379 }
1380 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001381 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001382 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001383 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001384 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001385 ConvertedType = ToType;
1386 return true;
1387 }
1388 // Objective C++: We're able to convert from a pointer to an
1389 // interface to a pointer to a different interface.
1390 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001391 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1392 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1393 if (getLangOptions().CPlusPlus && LHS && RHS &&
1394 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1395 FromObjCPtr->getPointeeType()))
1396 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001397 ConvertedType = ToType;
1398 return true;
1399 }
1400
1401 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1402 // Okay: this is some kind of implicit downcast of Objective-C
1403 // interfaces, which is permitted. However, we're going to
1404 // complain about it.
1405 IncompatibleObjC = true;
1406 ConvertedType = FromType;
1407 return true;
1408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001410 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001411 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001412 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001413 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001414 else if (const BlockPointerType *ToBlockPtr =
1415 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001416 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001417 // to a block pointer type.
1418 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1419 ConvertedType = ToType;
1420 return true;
1421 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001422 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001423 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001424 else if (FromType->getAs<BlockPointerType>() &&
1425 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1426 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001427 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001428 ConvertedType = ToType;
1429 return true;
1430 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001431 else
Douglas Gregora119f102008-12-19 19:13:09 +00001432 return false;
1433
Douglas Gregor033f56d2008-12-23 00:53:59 +00001434 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001435 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001436 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001437 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001438 FromPointeeType = FromBlockPtr->getPointeeType();
1439 else
Douglas Gregora119f102008-12-19 19:13:09 +00001440 return false;
1441
Douglas Gregora119f102008-12-19 19:13:09 +00001442 // If we have pointers to pointers, recursively check whether this
1443 // is an Objective-C conversion.
1444 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1445 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1446 IncompatibleObjC)) {
1447 // We always complain about this conversion.
1448 IncompatibleObjC = true;
1449 ConvertedType = ToType;
1450 return true;
1451 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001452 // Allow conversion of pointee being objective-c pointer to another one;
1453 // as in I* to id.
1454 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1455 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1456 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1457 IncompatibleObjC)) {
1458 ConvertedType = ToType;
1459 return true;
1460 }
1461
Douglas Gregor033f56d2008-12-23 00:53:59 +00001462 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001463 // differences in the argument and result types are in Objective-C
1464 // pointer conversions. If so, we permit the conversion (but
1465 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001466 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001467 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001468 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001469 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001470 if (FromFunctionType && ToFunctionType) {
1471 // If the function types are exactly the same, this isn't an
1472 // Objective-C pointer conversion.
1473 if (Context.getCanonicalType(FromPointeeType)
1474 == Context.getCanonicalType(ToPointeeType))
1475 return false;
1476
1477 // Perform the quick checks that will tell us whether these
1478 // function types are obviously different.
1479 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1480 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1481 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1482 return false;
1483
1484 bool HasObjCConversion = false;
1485 if (Context.getCanonicalType(FromFunctionType->getResultType())
1486 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1487 // Okay, the types match exactly. Nothing to do.
1488 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1489 ToFunctionType->getResultType(),
1490 ConvertedType, IncompatibleObjC)) {
1491 // Okay, we have an Objective-C pointer conversion.
1492 HasObjCConversion = true;
1493 } else {
1494 // Function types are too different. Abort.
1495 return false;
1496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
Douglas Gregora119f102008-12-19 19:13:09 +00001498 // Check argument types.
1499 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1500 ArgIdx != NumArgs; ++ArgIdx) {
1501 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1502 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1503 if (Context.getCanonicalType(FromArgType)
1504 == Context.getCanonicalType(ToArgType)) {
1505 // Okay, the types match exactly. Nothing to do.
1506 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1507 ConvertedType, IncompatibleObjC)) {
1508 // Okay, we have an Objective-C pointer conversion.
1509 HasObjCConversion = true;
1510 } else {
1511 // Argument types are too different. Abort.
1512 return false;
1513 }
1514 }
1515
1516 if (HasObjCConversion) {
1517 // We had an Objective-C conversion. Allow this pointer
1518 // conversion, but complain about it.
1519 ConvertedType = ToType;
1520 IncompatibleObjC = true;
1521 return true;
1522 }
1523 }
1524
Sebastian Redl72b597d2009-01-25 19:43:20 +00001525 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001526}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001527
1528/// FunctionArgTypesAreEqual - This routine checks two function proto types
1529/// for equlity of their argument types. Caller has already checked that
1530/// they have same number of arguments. This routine assumes that Objective-C
1531/// pointer types which only differ in their protocol qualifiers are equal.
1532bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1533 FunctionProtoType* NewType){
1534 if (!getLangOptions().ObjC1)
1535 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1536 NewType->arg_type_begin());
1537
1538 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1539 N = NewType->arg_type_begin(),
1540 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1541 QualType ToType = (*O);
1542 QualType FromType = (*N);
1543 if (ToType != FromType) {
1544 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1545 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001546 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1547 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1548 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1549 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001550 continue;
1551 }
1552 else if (ToType->isObjCObjectPointerType() &&
1553 FromType->isObjCObjectPointerType()) {
1554 QualType ToInterfaceTy = ToType->getPointeeType();
1555 QualType FromInterfaceTy = FromType->getPointeeType();
1556 if (const ObjCInterfaceType *OITTo =
1557 ToInterfaceTy->getAs<ObjCInterfaceType>())
1558 if (const ObjCInterfaceType *OITFr =
1559 FromInterfaceTy->getAs<ObjCInterfaceType>())
1560 if (OITTo->getDecl() == OITFr->getDecl())
1561 continue;
1562 }
1563 return false;
1564 }
1565 }
1566 return true;
1567}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001568
Douglas Gregor39c16d42008-10-24 04:54:22 +00001569/// CheckPointerConversion - Check the pointer conversion from the
1570/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001571/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001572/// conversions for which IsPointerConversion has already returned
1573/// true. It returns true and produces a diagnostic if there was an
1574/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001575bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001576 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001577 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001578 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001579 QualType FromType = From->getType();
1580
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001581 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1582 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001583 QualType FromPointeeType = FromPtrType->getPointeeType(),
1584 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001585
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001586 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1587 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001588 // We must have a derived-to-base conversion. Check an
1589 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001590 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1591 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001592 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001593 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001594 return true;
1595
1596 // The conversion was successful.
1597 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001598 }
1599 }
Mike Stump11289f42009-09-09 15:08:12 +00001600 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001601 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001602 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001603 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001604 // Objective-C++ conversions are always okay.
1605 // FIXME: We should have a different class of conversions for the
1606 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001607 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001608 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001609
Steve Naroff7cae42b2009-07-10 23:34:53 +00001610 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001611 return false;
1612}
1613
Sebastian Redl72b597d2009-01-25 19:43:20 +00001614/// IsMemberPointerConversion - Determines whether the conversion of the
1615/// expression From, which has the (possibly adjusted) type FromType, can be
1616/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1617/// If so, returns true and places the converted type (that might differ from
1618/// ToType in its cv-qualifiers at some level) into ConvertedType.
1619bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001620 QualType ToType,
1621 bool InOverloadResolution,
1622 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001623 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001624 if (!ToTypePtr)
1625 return false;
1626
1627 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001628 if (From->isNullPointerConstant(Context,
1629 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1630 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001631 ConvertedType = ToType;
1632 return true;
1633 }
1634
1635 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001636 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001637 if (!FromTypePtr)
1638 return false;
1639
1640 // A pointer to member of B can be converted to a pointer to member of D,
1641 // where D is derived from B (C++ 4.11p2).
1642 QualType FromClass(FromTypePtr->getClass(), 0);
1643 QualType ToClass(ToTypePtr->getClass(), 0);
1644 // FIXME: What happens when these are dependent? Is this function even called?
1645
1646 if (IsDerivedFrom(ToClass, FromClass)) {
1647 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1648 ToClass.getTypePtr());
1649 return true;
1650 }
1651
1652 return false;
1653}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001654
Sebastian Redl72b597d2009-01-25 19:43:20 +00001655/// CheckMemberPointerConversion - Check the member pointer conversion from the
1656/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001657/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001658/// for which IsMemberPointerConversion has already returned true. It returns
1659/// true and produces a diagnostic if there was an error, or returns false
1660/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001661bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001662 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001663 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001664 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001665 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001666 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001667 if (!FromPtrType) {
1668 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001669 assert(From->isNullPointerConstant(Context,
1670 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001671 "Expr must be null pointer constant!");
1672 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001673 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001674 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001675
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001676 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001677 assert(ToPtrType && "No member pointer cast has a target type "
1678 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001679
Sebastian Redled8f2002009-01-28 18:33:18 +00001680 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1681 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001682
Sebastian Redled8f2002009-01-28 18:33:18 +00001683 // FIXME: What about dependent types?
1684 assert(FromClass->isRecordType() && "Pointer into non-class.");
1685 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001686
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001687 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001688 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001689 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1690 assert(DerivationOkay &&
1691 "Should not have been called if derivation isn't OK.");
1692 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001693
Sebastian Redled8f2002009-01-28 18:33:18 +00001694 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1695 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001696 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1697 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1698 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1699 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001700 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001701
Douglas Gregor89ee6822009-02-28 01:32:25 +00001702 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001703 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1704 << FromClass << ToClass << QualType(VBase, 0)
1705 << From->getSourceRange();
1706 return true;
1707 }
1708
John McCall5b0829a2010-02-10 09:31:12 +00001709 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001710 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1711 Paths.front(),
1712 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001713
Anders Carlssond7923c62009-08-22 23:33:40 +00001714 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001715 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001716 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001717 return false;
1718}
1719
Douglas Gregor9a657932008-10-21 23:43:52 +00001720/// IsQualificationConversion - Determines whether the conversion from
1721/// an rvalue of type FromType to ToType is a qualification conversion
1722/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001723bool
1724Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001725 FromType = Context.getCanonicalType(FromType);
1726 ToType = Context.getCanonicalType(ToType);
1727
1728 // If FromType and ToType are the same type, this is not a
1729 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001730 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001731 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001732
Douglas Gregor9a657932008-10-21 23:43:52 +00001733 // (C++ 4.4p4):
1734 // A conversion can add cv-qualifiers at levels other than the first
1735 // in multi-level pointers, subject to the following rules: [...]
1736 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001737 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001738 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001739 // Within each iteration of the loop, we check the qualifiers to
1740 // determine if this still looks like a qualification
1741 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001742 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001743 // until there are no more pointers or pointers-to-members left to
1744 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001745 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001746
1747 // -- for every j > 0, if const is in cv 1,j then const is in cv
1748 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001749 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001750 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001751
Douglas Gregor9a657932008-10-21 23:43:52 +00001752 // -- if the cv 1,j and cv 2,j are different, then const is in
1753 // every cv for 0 < k < j.
1754 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001755 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001756 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001757
Douglas Gregor9a657932008-10-21 23:43:52 +00001758 // Keep track of whether all prior cv-qualifiers in the "to" type
1759 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001760 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001761 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001762 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001763
1764 // We are left with FromType and ToType being the pointee types
1765 // after unwrapping the original FromType and ToType the same number
1766 // of types. If we unwrapped any pointers, and if FromType and
1767 // ToType have the same unqualified type (since we checked
1768 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001769 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001770}
1771
Douglas Gregor576e98c2009-01-30 23:27:23 +00001772/// Determines whether there is a user-defined conversion sequence
1773/// (C++ [over.ics.user]) that converts expression From to the type
1774/// ToType. If such a conversion exists, User will contain the
1775/// user-defined conversion sequence that performs such a conversion
1776/// and this routine will return true. Otherwise, this routine returns
1777/// false and User is unspecified.
1778///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001779/// \param AllowExplicit true if the conversion should consider C++0x
1780/// "explicit" conversion functions as well as non-explicit conversion
1781/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001782OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1783 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001784 OverloadCandidateSet& CandidateSet,
1785 bool AllowExplicit) {
1786 // Whether we will only visit constructors.
1787 bool ConstructorsOnly = false;
1788
1789 // If the type we are conversion to is a class type, enumerate its
1790 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001791 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001792 // C++ [over.match.ctor]p1:
1793 // When objects of class type are direct-initialized (8.5), or
1794 // copy-initialized from an expression of the same or a
1795 // derived class type (8.5), overload resolution selects the
1796 // constructor. [...] For copy-initialization, the candidate
1797 // functions are all the converting constructors (12.3.1) of
1798 // that class. The argument list is the expression-list within
1799 // the parentheses of the initializer.
1800 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1801 (From->getType()->getAs<RecordType>() &&
1802 IsDerivedFrom(From->getType(), ToType)))
1803 ConstructorsOnly = true;
1804
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001805 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1806 // We're not going to find any constructors.
1807 } else if (CXXRecordDecl *ToRecordDecl
1808 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001809 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001810 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001811 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001812 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001813 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001814 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001815 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001816 NamedDecl *D = *Con;
1817 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1818
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001819 // Find the constructor (which may be a template).
1820 CXXConstructorDecl *Constructor = 0;
1821 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001822 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001823 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001824 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001825 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1826 else
John McCalla0296f72010-03-19 07:35:19 +00001827 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001828
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001829 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001830 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001831 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001832 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001833 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001834 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001835 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001836 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001837 // Allow one user-defined conversion when user specifies a
1838 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001839 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001840 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001841 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001842 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001843 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001844 }
1845 }
1846
Douglas Gregor5ab11652010-04-17 22:01:05 +00001847 // Enumerate conversion functions, if we're allowed to.
1848 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001849 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001850 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001851 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001852 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001853 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001854 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001855 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1856 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001857 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001858 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001859 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001860 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001861 DeclAccessPair FoundDecl = I.getPair();
1862 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001863 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1864 if (isa<UsingShadowDecl>(D))
1865 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1866
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001867 CXXConversionDecl *Conv;
1868 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001869 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1870 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001871 else
John McCallda4458e2010-03-31 01:36:47 +00001872 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001873
1874 if (AllowExplicit || !Conv->isExplicit()) {
1875 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001876 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001877 ActingContext, From, ToType,
1878 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001879 else
John McCalla0296f72010-03-19 07:35:19 +00001880 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001881 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001882 }
1883 }
1884 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001885 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001886
1887 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001888 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001889 case OR_Success:
1890 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001891 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001892 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1893 // C++ [over.ics.user]p1:
1894 // If the user-defined conversion is specified by a
1895 // constructor (12.3.1), the initial standard conversion
1896 // sequence converts the source type to the type required by
1897 // the argument of the constructor.
1898 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001899 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001900 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001901 User.EllipsisConversion = true;
1902 else {
1903 User.Before = Best->Conversions[0].Standard;
1904 User.EllipsisConversion = false;
1905 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001906 User.ConversionFunction = Constructor;
1907 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001908 User.After.setFromType(
1909 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001910 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001911 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001912 } else if (CXXConversionDecl *Conversion
1913 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1914 // C++ [over.ics.user]p1:
1915 //
1916 // [...] If the user-defined conversion is specified by a
1917 // conversion function (12.3.2), the initial standard
1918 // conversion sequence converts the source type to the
1919 // implicit object parameter of the conversion function.
1920 User.Before = Best->Conversions[0].Standard;
1921 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001922 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001923
1924 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001925 // The second standard conversion sequence converts the
1926 // result of the user-defined conversion to the target type
1927 // for the sequence. Since an implicit conversion sequence
1928 // is an initialization, the special rules for
1929 // initialization by user-defined conversion apply when
1930 // selecting the best user-defined conversion for a
1931 // user-defined conversion sequence (see 13.3.3 and
1932 // 13.3.3.1).
1933 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001934 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001935 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001936 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001937 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001938 }
Mike Stump11289f42009-09-09 15:08:12 +00001939
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001940 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001941 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001942 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001943 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001944 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001945
1946 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001947 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001948 }
1949
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001950 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001951}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001952
1953bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001954Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001955 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001956 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001957 OverloadingResult OvResult =
1958 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001959 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001960 if (OvResult == OR_Ambiguous)
1961 Diag(From->getSourceRange().getBegin(),
1962 diag::err_typecheck_ambiguous_condition)
1963 << From->getType() << ToType << From->getSourceRange();
1964 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1965 Diag(From->getSourceRange().getBegin(),
1966 diag::err_typecheck_nonviable_condition)
1967 << From->getType() << ToType << From->getSourceRange();
1968 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001969 return false;
John McCallad907772010-01-12 07:18:19 +00001970 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001971 return true;
1972}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001973
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001974/// CompareImplicitConversionSequences - Compare two implicit
1975/// conversion sequences to determine whether one is better than the
1976/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001977ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001978Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1979 const ImplicitConversionSequence& ICS2)
1980{
1981 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1982 // conversion sequences (as defined in 13.3.3.1)
1983 // -- a standard conversion sequence (13.3.3.1.1) is a better
1984 // conversion sequence than a user-defined conversion sequence or
1985 // an ellipsis conversion sequence, and
1986 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1987 // conversion sequence than an ellipsis conversion sequence
1988 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001989 //
John McCall0d1da222010-01-12 00:44:57 +00001990 // C++0x [over.best.ics]p10:
1991 // For the purpose of ranking implicit conversion sequences as
1992 // described in 13.3.3.2, the ambiguous conversion sequence is
1993 // treated as a user-defined sequence that is indistinguishable
1994 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00001995 if (ICS1.getKindRank() < ICS2.getKindRank())
1996 return ImplicitConversionSequence::Better;
1997 else if (ICS2.getKindRank() < ICS1.getKindRank())
1998 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001999
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002000 // The following checks require both conversion sequences to be of
2001 // the same kind.
2002 if (ICS1.getKind() != ICS2.getKind())
2003 return ImplicitConversionSequence::Indistinguishable;
2004
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002005 // Two implicit conversion sequences of the same form are
2006 // indistinguishable conversion sequences unless one of the
2007 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002008 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002009 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002010 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002011 // User-defined conversion sequence U1 is a better conversion
2012 // sequence than another user-defined conversion sequence U2 if
2013 // they contain the same user-defined conversion function or
2014 // constructor and if the second standard conversion sequence of
2015 // U1 is better than the second standard conversion sequence of
2016 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002017 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018 ICS2.UserDefined.ConversionFunction)
2019 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2020 ICS2.UserDefined.After);
2021 }
2022
2023 return ImplicitConversionSequence::Indistinguishable;
2024}
2025
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002026// Per 13.3.3.2p3, compare the given standard conversion sequences to
2027// determine if one is a proper subset of the other.
2028static ImplicitConversionSequence::CompareKind
2029compareStandardConversionSubsets(ASTContext &Context,
2030 const StandardConversionSequence& SCS1,
2031 const StandardConversionSequence& SCS2) {
2032 ImplicitConversionSequence::CompareKind Result
2033 = ImplicitConversionSequence::Indistinguishable;
2034
2035 if (SCS1.Second != SCS2.Second) {
2036 if (SCS1.Second == ICK_Identity)
2037 Result = ImplicitConversionSequence::Better;
2038 else if (SCS2.Second == ICK_Identity)
2039 Result = ImplicitConversionSequence::Worse;
2040 else
2041 return ImplicitConversionSequence::Indistinguishable;
2042 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
2043 return ImplicitConversionSequence::Indistinguishable;
2044
2045 if (SCS1.Third == SCS2.Third) {
2046 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2047 : ImplicitConversionSequence::Indistinguishable;
2048 }
2049
2050 if (SCS1.Third == ICK_Identity)
2051 return Result == ImplicitConversionSequence::Worse
2052 ? ImplicitConversionSequence::Indistinguishable
2053 : ImplicitConversionSequence::Better;
2054
2055 if (SCS2.Third == ICK_Identity)
2056 return Result == ImplicitConversionSequence::Better
2057 ? ImplicitConversionSequence::Indistinguishable
2058 : ImplicitConversionSequence::Worse;
2059
2060 return ImplicitConversionSequence::Indistinguishable;
2061}
2062
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002063/// CompareStandardConversionSequences - Compare two standard
2064/// conversion sequences to determine whether one is better than the
2065/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002066ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002067Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2068 const StandardConversionSequence& SCS2)
2069{
2070 // Standard conversion sequence S1 is a better conversion sequence
2071 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2072
2073 // -- S1 is a proper subsequence of S2 (comparing the conversion
2074 // sequences in the canonical form defined by 13.3.3.1.1,
2075 // excluding any Lvalue Transformation; the identity conversion
2076 // sequence is considered to be a subsequence of any
2077 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002078 if (ImplicitConversionSequence::CompareKind CK
2079 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2080 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002081
2082 // -- the rank of S1 is better than the rank of S2 (by the rules
2083 // defined below), or, if not that,
2084 ImplicitConversionRank Rank1 = SCS1.getRank();
2085 ImplicitConversionRank Rank2 = SCS2.getRank();
2086 if (Rank1 < Rank2)
2087 return ImplicitConversionSequence::Better;
2088 else if (Rank2 < Rank1)
2089 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002090
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002091 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2092 // are indistinguishable unless one of the following rules
2093 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002094
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002095 // A conversion that is not a conversion of a pointer, or
2096 // pointer to member, to bool is better than another conversion
2097 // that is such a conversion.
2098 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2099 return SCS2.isPointerConversionToBool()
2100 ? ImplicitConversionSequence::Better
2101 : ImplicitConversionSequence::Worse;
2102
Douglas Gregor5c407d92008-10-23 00:40:37 +00002103 // C++ [over.ics.rank]p4b2:
2104 //
2105 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002106 // conversion of B* to A* is better than conversion of B* to
2107 // void*, and conversion of A* to void* is better than conversion
2108 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002109 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002110 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002111 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002112 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002113 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2114 // Exactly one of the conversion sequences is a conversion to
2115 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002116 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2117 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002118 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2119 // Neither conversion sequence converts to a void pointer; compare
2120 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002121 if (ImplicitConversionSequence::CompareKind DerivedCK
2122 = CompareDerivedToBaseConversions(SCS1, SCS2))
2123 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002124 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2125 // Both conversion sequences are conversions to void
2126 // pointers. Compare the source types to determine if there's an
2127 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002128 QualType FromType1 = SCS1.getFromType();
2129 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002130
2131 // Adjust the types we're converting from via the array-to-pointer
2132 // conversion, if we need to.
2133 if (SCS1.First == ICK_Array_To_Pointer)
2134 FromType1 = Context.getArrayDecayedType(FromType1);
2135 if (SCS2.First == ICK_Array_To_Pointer)
2136 FromType2 = Context.getArrayDecayedType(FromType2);
2137
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002138 QualType FromPointee1
2139 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2140 QualType FromPointee2
2141 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002142
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002143 if (IsDerivedFrom(FromPointee2, FromPointee1))
2144 return ImplicitConversionSequence::Better;
2145 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2146 return ImplicitConversionSequence::Worse;
2147
2148 // Objective-C++: If one interface is more specific than the
2149 // other, it is the better one.
2150 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2151 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2152 if (FromIface1 && FromIface1) {
2153 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2154 return ImplicitConversionSequence::Better;
2155 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2156 return ImplicitConversionSequence::Worse;
2157 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002158 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002159
2160 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2161 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002162 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002163 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002164 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002165
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002166 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002167 // C++0x [over.ics.rank]p3b4:
2168 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2169 // implicit object parameter of a non-static member function declared
2170 // without a ref-qualifier, and S1 binds an rvalue reference to an
2171 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002172 // FIXME: We don't know if we're dealing with the implicit object parameter,
2173 // or if the member function in this case has a ref qualifier.
2174 // (Of course, we don't have ref qualifiers yet.)
2175 if (SCS1.RRefBinding != SCS2.RRefBinding)
2176 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2177 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002178
2179 // C++ [over.ics.rank]p3b4:
2180 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2181 // which the references refer are the same type except for
2182 // top-level cv-qualifiers, and the type to which the reference
2183 // initialized by S2 refers is more cv-qualified than the type
2184 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002185 QualType T1 = SCS1.getToType(2);
2186 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002187 T1 = Context.getCanonicalType(T1);
2188 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002189 Qualifiers T1Quals, T2Quals;
2190 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2191 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2192 if (UnqualT1 == UnqualT2) {
2193 // If the type is an array type, promote the element qualifiers to the type
2194 // for comparison.
2195 if (isa<ArrayType>(T1) && T1Quals)
2196 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2197 if (isa<ArrayType>(T2) && T2Quals)
2198 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002199 if (T2.isMoreQualifiedThan(T1))
2200 return ImplicitConversionSequence::Better;
2201 else if (T1.isMoreQualifiedThan(T2))
2202 return ImplicitConversionSequence::Worse;
2203 }
2204 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002205
2206 return ImplicitConversionSequence::Indistinguishable;
2207}
2208
2209/// CompareQualificationConversions - Compares two standard conversion
2210/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002211/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2212ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002213Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002214 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002215 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002216 // -- S1 and S2 differ only in their qualification conversion and
2217 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2218 // cv-qualification signature of type T1 is a proper subset of
2219 // the cv-qualification signature of type T2, and S1 is not the
2220 // deprecated string literal array-to-pointer conversion (4.2).
2221 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2222 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2223 return ImplicitConversionSequence::Indistinguishable;
2224
2225 // FIXME: the example in the standard doesn't use a qualification
2226 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002227 QualType T1 = SCS1.getToType(2);
2228 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002229 T1 = Context.getCanonicalType(T1);
2230 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002231 Qualifiers T1Quals, T2Quals;
2232 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2233 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002234
2235 // If the types are the same, we won't learn anything by unwrapped
2236 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002237 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002238 return ImplicitConversionSequence::Indistinguishable;
2239
Chandler Carruth607f38e2009-12-29 07:16:59 +00002240 // If the type is an array type, promote the element qualifiers to the type
2241 // for comparison.
2242 if (isa<ArrayType>(T1) && T1Quals)
2243 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2244 if (isa<ArrayType>(T2) && T2Quals)
2245 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2246
Mike Stump11289f42009-09-09 15:08:12 +00002247 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002248 = ImplicitConversionSequence::Indistinguishable;
2249 while (UnwrapSimilarPointerTypes(T1, T2)) {
2250 // Within each iteration of the loop, we check the qualifiers to
2251 // determine if this still looks like a qualification
2252 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002253 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002254 // until there are no more pointers or pointers-to-members left
2255 // to unwrap. This essentially mimics what
2256 // IsQualificationConversion does, but here we're checking for a
2257 // strict subset of qualifiers.
2258 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2259 // The qualifiers are the same, so this doesn't tell us anything
2260 // about how the sequences rank.
2261 ;
2262 else if (T2.isMoreQualifiedThan(T1)) {
2263 // T1 has fewer qualifiers, so it could be the better sequence.
2264 if (Result == ImplicitConversionSequence::Worse)
2265 // Neither has qualifiers that are a subset of the other's
2266 // qualifiers.
2267 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002268
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002269 Result = ImplicitConversionSequence::Better;
2270 } else if (T1.isMoreQualifiedThan(T2)) {
2271 // T2 has fewer qualifiers, so it could be the better sequence.
2272 if (Result == ImplicitConversionSequence::Better)
2273 // Neither has qualifiers that are a subset of the other's
2274 // qualifiers.
2275 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002276
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002277 Result = ImplicitConversionSequence::Worse;
2278 } else {
2279 // Qualifiers are disjoint.
2280 return ImplicitConversionSequence::Indistinguishable;
2281 }
2282
2283 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002284 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002285 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002286 }
2287
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002288 // Check that the winning standard conversion sequence isn't using
2289 // the deprecated string literal array to pointer conversion.
2290 switch (Result) {
2291 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002292 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002293 Result = ImplicitConversionSequence::Indistinguishable;
2294 break;
2295
2296 case ImplicitConversionSequence::Indistinguishable:
2297 break;
2298
2299 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002300 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002301 Result = ImplicitConversionSequence::Indistinguishable;
2302 break;
2303 }
2304
2305 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002306}
2307
Douglas Gregor5c407d92008-10-23 00:40:37 +00002308/// CompareDerivedToBaseConversions - Compares two standard conversion
2309/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002310/// various kinds of derived-to-base conversions (C++
2311/// [over.ics.rank]p4b3). As part of these checks, we also look at
2312/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002313ImplicitConversionSequence::CompareKind
2314Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2315 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002316 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002317 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002318 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002319 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002320
2321 // Adjust the types we're converting from via the array-to-pointer
2322 // conversion, if we need to.
2323 if (SCS1.First == ICK_Array_To_Pointer)
2324 FromType1 = Context.getArrayDecayedType(FromType1);
2325 if (SCS2.First == ICK_Array_To_Pointer)
2326 FromType2 = Context.getArrayDecayedType(FromType2);
2327
2328 // Canonicalize all of the types.
2329 FromType1 = Context.getCanonicalType(FromType1);
2330 ToType1 = Context.getCanonicalType(ToType1);
2331 FromType2 = Context.getCanonicalType(FromType2);
2332 ToType2 = Context.getCanonicalType(ToType2);
2333
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002334 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002335 //
2336 // If class B is derived directly or indirectly from class A and
2337 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002338 //
2339 // For Objective-C, we let A, B, and C also be Objective-C
2340 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002341
2342 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002343 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002344 SCS2.Second == ICK_Pointer_Conversion &&
2345 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2346 FromType1->isPointerType() && FromType2->isPointerType() &&
2347 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002348 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002349 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002350 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002351 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002352 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002353 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002354 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002355 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002356
John McCall9dd450b2009-09-21 23:43:11 +00002357 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2358 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2359 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2360 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002361
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002362 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002363 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2364 if (IsDerivedFrom(ToPointee1, ToPointee2))
2365 return ImplicitConversionSequence::Better;
2366 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2367 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002368
2369 if (ToIface1 && ToIface2) {
2370 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2371 return ImplicitConversionSequence::Better;
2372 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2373 return ImplicitConversionSequence::Worse;
2374 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002375 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002376
2377 // -- conversion of B* to A* is better than conversion of C* to A*,
2378 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2379 if (IsDerivedFrom(FromPointee2, FromPointee1))
2380 return ImplicitConversionSequence::Better;
2381 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2382 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002383
Douglas Gregor237f96c2008-11-26 23:31:11 +00002384 if (FromIface1 && FromIface2) {
2385 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2386 return ImplicitConversionSequence::Better;
2387 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2388 return ImplicitConversionSequence::Worse;
2389 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002390 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002391 }
2392
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002393 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002394 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2395 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2396 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2397 const MemberPointerType * FromMemPointer1 =
2398 FromType1->getAs<MemberPointerType>();
2399 const MemberPointerType * ToMemPointer1 =
2400 ToType1->getAs<MemberPointerType>();
2401 const MemberPointerType * FromMemPointer2 =
2402 FromType2->getAs<MemberPointerType>();
2403 const MemberPointerType * ToMemPointer2 =
2404 ToType2->getAs<MemberPointerType>();
2405 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2406 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2407 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2408 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2409 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2410 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2411 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2412 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002413 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002414 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2415 if (IsDerivedFrom(ToPointee1, ToPointee2))
2416 return ImplicitConversionSequence::Worse;
2417 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2418 return ImplicitConversionSequence::Better;
2419 }
2420 // conversion of B::* to C::* is better than conversion of A::* to C::*
2421 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2422 if (IsDerivedFrom(FromPointee1, FromPointee2))
2423 return ImplicitConversionSequence::Better;
2424 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2425 return ImplicitConversionSequence::Worse;
2426 }
2427 }
2428
Douglas Gregor5ab11652010-04-17 22:01:05 +00002429 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002430 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002431 // -- binding of an expression of type C to a reference of type
2432 // B& is better than binding an expression of type C to a
2433 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002434 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2435 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002436 if (IsDerivedFrom(ToType1, ToType2))
2437 return ImplicitConversionSequence::Better;
2438 else if (IsDerivedFrom(ToType2, ToType1))
2439 return ImplicitConversionSequence::Worse;
2440 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002441
Douglas Gregor2fe98832008-11-03 19:09:14 +00002442 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002443 // -- binding of an expression of type B to a reference of type
2444 // A& is better than binding an expression of type C to a
2445 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002446 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2447 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002448 if (IsDerivedFrom(FromType2, FromType1))
2449 return ImplicitConversionSequence::Better;
2450 else if (IsDerivedFrom(FromType1, FromType2))
2451 return ImplicitConversionSequence::Worse;
2452 }
2453 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002454
Douglas Gregor5c407d92008-10-23 00:40:37 +00002455 return ImplicitConversionSequence::Indistinguishable;
2456}
2457
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002458/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2459/// determine whether they are reference-related,
2460/// reference-compatible, reference-compatible with added
2461/// qualification, or incompatible, for use in C++ initialization by
2462/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2463/// type, and the first type (T1) is the pointee type of the reference
2464/// type being initialized.
2465Sema::ReferenceCompareResult
2466Sema::CompareReferenceRelationship(SourceLocation Loc,
2467 QualType OrigT1, QualType OrigT2,
2468 bool& DerivedToBase) {
2469 assert(!OrigT1->isReferenceType() &&
2470 "T1 must be the pointee type of the reference type");
2471 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2472
2473 QualType T1 = Context.getCanonicalType(OrigT1);
2474 QualType T2 = Context.getCanonicalType(OrigT2);
2475 Qualifiers T1Quals, T2Quals;
2476 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2477 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2478
2479 // C++ [dcl.init.ref]p4:
2480 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2481 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2482 // T1 is a base class of T2.
2483 if (UnqualT1 == UnqualT2)
2484 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002485 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002486 IsDerivedFrom(UnqualT2, UnqualT1))
2487 DerivedToBase = true;
2488 else
2489 return Ref_Incompatible;
2490
2491 // At this point, we know that T1 and T2 are reference-related (at
2492 // least).
2493
2494 // If the type is an array type, promote the element qualifiers to the type
2495 // for comparison.
2496 if (isa<ArrayType>(T1) && T1Quals)
2497 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2498 if (isa<ArrayType>(T2) && T2Quals)
2499 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2500
2501 // C++ [dcl.init.ref]p4:
2502 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2503 // reference-related to T2 and cv1 is the same cv-qualification
2504 // as, or greater cv-qualification than, cv2. For purposes of
2505 // overload resolution, cases for which cv1 is greater
2506 // cv-qualification than cv2 are identified as
2507 // reference-compatible with added qualification (see 13.3.3.2).
2508 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2509 return Ref_Compatible;
2510 else if (T1.isMoreQualifiedThan(T2))
2511 return Ref_Compatible_With_Added_Qualification;
2512 else
2513 return Ref_Related;
2514}
2515
2516/// \brief Compute an implicit conversion sequence for reference
2517/// initialization.
2518static ImplicitConversionSequence
2519TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2520 SourceLocation DeclLoc,
2521 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002522 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002523 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2524
2525 // Most paths end in a failed conversion.
2526 ImplicitConversionSequence ICS;
2527 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2528
2529 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2530 QualType T2 = Init->getType();
2531
2532 // If the initializer is the address of an overloaded function, try
2533 // to resolve the overloaded function. If all goes well, T2 is the
2534 // type of the resulting function.
2535 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2536 DeclAccessPair Found;
2537 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2538 false, Found))
2539 T2 = Fn->getType();
2540 }
2541
2542 // Compute some basic properties of the types and the initializer.
2543 bool isRValRef = DeclType->isRValueReferenceType();
2544 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002545 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002546 Sema::ReferenceCompareResult RefRelationship
2547 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2548
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002549
2550 // C++ [over.ics.ref]p3:
2551 // Except for an implicit object parameter, for which see 13.3.1,
2552 // a standard conversion sequence cannot be formed if it requires
2553 // binding an lvalue reference to non-const to an rvalue or
2554 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002555 //
2556 // FIXME: DPG doesn't trust this code. It seems far too early to
2557 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002558 if (isRValRef && InitLvalue == Expr::LV_Valid)
2559 return ICS;
2560
Douglas Gregor870f3742010-04-18 09:22:00 +00002561 // C++0x [dcl.init.ref]p16:
2562 // A reference to type "cv1 T1" is initialized by an expression
2563 // of type "cv2 T2" as follows:
2564
2565 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002566 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2567 // reference-compatible with "cv2 T2," or
2568 //
2569 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2570 if (InitLvalue == Expr::LV_Valid &&
2571 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2572 // C++ [over.ics.ref]p1:
2573 // When a parameter of reference type binds directly (8.5.3)
2574 // to an argument expression, the implicit conversion sequence
2575 // is the identity conversion, unless the argument expression
2576 // has a type that is a derived class of the parameter type,
2577 // in which case the implicit conversion sequence is a
2578 // derived-to-base Conversion (13.3.3.1).
2579 ICS.setStandard();
2580 ICS.Standard.First = ICK_Identity;
2581 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2582 ICS.Standard.Third = ICK_Identity;
2583 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2584 ICS.Standard.setToType(0, T2);
2585 ICS.Standard.setToType(1, T1);
2586 ICS.Standard.setToType(2, T1);
2587 ICS.Standard.ReferenceBinding = true;
2588 ICS.Standard.DirectBinding = true;
2589 ICS.Standard.RRefBinding = false;
2590 ICS.Standard.CopyConstructor = 0;
2591
2592 // Nothing more to do: the inaccessibility/ambiguity check for
2593 // derived-to-base conversions is suppressed when we're
2594 // computing the implicit conversion sequence (C++
2595 // [over.best.ics]p2).
2596 return ICS;
2597 }
2598
2599 // -- has a class type (i.e., T2 is a class type), where T1 is
2600 // not reference-related to T2, and can be implicitly
2601 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2602 // is reference-compatible with "cv3 T3" 92) (this
2603 // conversion is selected by enumerating the applicable
2604 // conversion functions (13.3.1.6) and choosing the best
2605 // one through overload resolution (13.3)),
2606 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2607 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2608 RefRelationship == Sema::Ref_Incompatible) {
2609 CXXRecordDecl *T2RecordDecl
2610 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2611
2612 OverloadCandidateSet CandidateSet(DeclLoc);
2613 const UnresolvedSetImpl *Conversions
2614 = T2RecordDecl->getVisibleConversionFunctions();
2615 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2616 E = Conversions->end(); I != E; ++I) {
2617 NamedDecl *D = *I;
2618 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2619 if (isa<UsingShadowDecl>(D))
2620 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2621
2622 FunctionTemplateDecl *ConvTemplate
2623 = dyn_cast<FunctionTemplateDecl>(D);
2624 CXXConversionDecl *Conv;
2625 if (ConvTemplate)
2626 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2627 else
2628 Conv = cast<CXXConversionDecl>(D);
2629
2630 // If the conversion function doesn't return a reference type,
2631 // it can't be considered for this conversion.
2632 if (Conv->getConversionType()->isLValueReferenceType() &&
2633 (AllowExplicit || !Conv->isExplicit())) {
2634 if (ConvTemplate)
2635 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2636 Init, DeclType, CandidateSet);
2637 else
2638 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2639 DeclType, CandidateSet);
2640 }
2641 }
2642
2643 OverloadCandidateSet::iterator Best;
2644 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2645 case OR_Success:
2646 // C++ [over.ics.ref]p1:
2647 //
2648 // [...] If the parameter binds directly to the result of
2649 // applying a conversion function to the argument
2650 // expression, the implicit conversion sequence is a
2651 // user-defined conversion sequence (13.3.3.1.2), with the
2652 // second standard conversion sequence either an identity
2653 // conversion or, if the conversion function returns an
2654 // entity of a type that is a derived class of the parameter
2655 // type, a derived-to-base Conversion.
2656 if (!Best->FinalConversion.DirectBinding)
2657 break;
2658
2659 ICS.setUserDefined();
2660 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2661 ICS.UserDefined.After = Best->FinalConversion;
2662 ICS.UserDefined.ConversionFunction = Best->Function;
2663 ICS.UserDefined.EllipsisConversion = false;
2664 assert(ICS.UserDefined.After.ReferenceBinding &&
2665 ICS.UserDefined.After.DirectBinding &&
2666 "Expected a direct reference binding!");
2667 return ICS;
2668
2669 case OR_Ambiguous:
2670 ICS.setAmbiguous();
2671 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2672 Cand != CandidateSet.end(); ++Cand)
2673 if (Cand->Viable)
2674 ICS.Ambiguous.addConversion(Cand->Function);
2675 return ICS;
2676
2677 case OR_No_Viable_Function:
2678 case OR_Deleted:
2679 // There was no suitable conversion, or we found a deleted
2680 // conversion; continue with other checks.
2681 break;
2682 }
2683 }
2684
2685 // -- Otherwise, the reference shall be to a non-volatile const
2686 // type (i.e., cv1 shall be const), or the reference shall be an
2687 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002688 //
2689 // We actually handle one oddity of C++ [over.ics.ref] at this
2690 // point, which is that, due to p2 (which short-circuits reference
2691 // binding by only attempting a simple conversion for non-direct
2692 // bindings) and p3's strange wording, we allow a const volatile
2693 // reference to bind to an rvalue. Hence the check for the presence
2694 // of "const" rather than checking for "const" being the only
2695 // qualifier.
2696 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002697 return ICS;
2698
Douglas Gregorf93df192010-04-18 08:46:23 +00002699 // -- if T2 is a class type and
2700 // -- the initializer expression is an rvalue and "cv1 T1"
2701 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002702 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002703 // -- T1 is not reference-related to T2 and the initializer
2704 // expression can be implicitly converted to an rvalue
2705 // of type "cv3 T3" (this conversion is selected by
2706 // enumerating the applicable conversion functions
2707 // (13.3.1.6) and choosing the best one through overload
2708 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002709 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002710 // then the reference is bound to the initializer
2711 // expression rvalue in the first case and to the object
2712 // that is the result of the conversion in the second case
2713 // (or, in either case, to the appropriate base class
2714 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002715 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002716 // We're only checking the first case here, which is a direct
2717 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002718 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2719 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2720 ICS.setStandard();
2721 ICS.Standard.First = ICK_Identity;
2722 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2723 ICS.Standard.Third = ICK_Identity;
2724 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2725 ICS.Standard.setToType(0, T2);
2726 ICS.Standard.setToType(1, T1);
2727 ICS.Standard.setToType(2, T1);
2728 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002729 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002730 ICS.Standard.RRefBinding = isRValRef;
2731 ICS.Standard.CopyConstructor = 0;
2732 return ICS;
2733 }
2734
2735 // -- Otherwise, a temporary of type "cv1 T1" is created and
2736 // initialized from the initializer expression using the
2737 // rules for a non-reference copy initialization (8.5). The
2738 // reference is then bound to the temporary. If T1 is
2739 // reference-related to T2, cv1 must be the same
2740 // cv-qualification as, or greater cv-qualification than,
2741 // cv2; otherwise, the program is ill-formed.
2742 if (RefRelationship == Sema::Ref_Related) {
2743 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2744 // we would be reference-compatible or reference-compatible with
2745 // added qualification. But that wasn't the case, so the reference
2746 // initialization fails.
2747 return ICS;
2748 }
2749
2750 // If at least one of the types is a class type, the types are not
2751 // related, and we aren't allowed any user conversions, the
2752 // reference binding fails. This case is important for breaking
2753 // recursion, since TryImplicitConversion below will attempt to
2754 // create a temporary through the use of a copy constructor.
2755 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2756 (T1->isRecordType() || T2->isRecordType()))
2757 return ICS;
2758
2759 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002760 // When a parameter of reference type is not bound directly to
2761 // an argument expression, the conversion sequence is the one
2762 // required to convert the argument expression to the
2763 // underlying type of the reference according to
2764 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2765 // to copy-initializing a temporary of the underlying type with
2766 // the argument expression. Any difference in top-level
2767 // cv-qualification is subsumed by the initialization itself
2768 // and does not constitute a conversion.
2769 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2770 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002771 /*InOverloadResolution=*/false);
2772
2773 // Of course, that's still a reference binding.
2774 if (ICS.isStandard()) {
2775 ICS.Standard.ReferenceBinding = true;
2776 ICS.Standard.RRefBinding = isRValRef;
2777 } else if (ICS.isUserDefined()) {
2778 ICS.UserDefined.After.ReferenceBinding = true;
2779 ICS.UserDefined.After.RRefBinding = isRValRef;
2780 }
2781 return ICS;
2782}
2783
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002784/// TryCopyInitialization - Try to copy-initialize a value of type
2785/// ToType from the expression From. Return the implicit conversion
2786/// sequence required to pass this argument, which may be a bad
2787/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002788/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002789/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002790static ImplicitConversionSequence
2791TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002792 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002793 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002794 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002795 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002796 /*FIXME:*/From->getLocStart(),
2797 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002798 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002799
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002800 return S.TryImplicitConversion(From, ToType,
2801 SuppressUserConversions,
2802 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002803 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002804}
2805
Douglas Gregor436424c2008-11-18 23:14:02 +00002806/// TryObjectArgumentInitialization - Try to initialize the object
2807/// parameter of the given member function (@c Method) from the
2808/// expression @p From.
2809ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002810Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002811 CXXMethodDecl *Method,
2812 CXXRecordDecl *ActingContext) {
2813 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002814 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2815 // const volatile object.
2816 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2817 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2818 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002819
2820 // Set up the conversion sequence as a "bad" conversion, to allow us
2821 // to exit early.
2822 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002823
2824 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002825 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002826 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002827 FromType = PT->getPointeeType();
2828
2829 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002830
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002831 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002832 // where X is the class of which the function is a member
2833 // (C++ [over.match.funcs]p4). However, when finding an implicit
2834 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002835 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002836 // (C++ [over.match.funcs]p5). We perform a simplified version of
2837 // reference binding here, that allows class rvalues to bind to
2838 // non-constant references.
2839
2840 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2841 // with the implicit object parameter (C++ [over.match.funcs]p5).
2842 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002843 if (ImplicitParamType.getCVRQualifiers()
2844 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002845 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002846 ICS.setBad(BadConversionSequence::bad_qualifiers,
2847 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002848 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002849 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002850
2851 // Check that we have either the same type or a derived type. It
2852 // affects the conversion rank.
2853 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002854 ImplicitConversionKind SecondKind;
2855 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2856 SecondKind = ICK_Identity;
2857 } else if (IsDerivedFrom(FromType, ClassType))
2858 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002859 else {
John McCall65eb8792010-02-25 01:37:24 +00002860 ICS.setBad(BadConversionSequence::unrelated_class,
2861 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002862 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002863 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002864
2865 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002866 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002867 ICS.Standard.setAsIdentityConversion();
2868 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002869 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002870 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002871 ICS.Standard.ReferenceBinding = true;
2872 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002873 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002874 return ICS;
2875}
2876
2877/// PerformObjectArgumentInitialization - Perform initialization of
2878/// the implicit object parameter for the given Method with the given
2879/// expression.
2880bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002881Sema::PerformObjectArgumentInitialization(Expr *&From,
2882 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002883 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002884 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002885 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002886 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002887 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002888
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002889 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002890 FromRecordType = PT->getPointeeType();
2891 DestType = Method->getThisType(Context);
2892 } else {
2893 FromRecordType = From->getType();
2894 DestType = ImplicitParamRecordType;
2895 }
2896
John McCall6e9f8f62009-12-03 04:06:58 +00002897 // Note that we always use the true parent context when performing
2898 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002899 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002900 = TryObjectArgumentInitialization(From->getType(), Method,
2901 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002902 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002903 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002904 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002905 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002906
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002907 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002908 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002909
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002910 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002911 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2912 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002913 return false;
2914}
2915
Douglas Gregor5fb53972009-01-14 15:45:31 +00002916/// TryContextuallyConvertToBool - Attempt to contextually convert the
2917/// expression From to bool (C++0x [conv]p3).
2918ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002919 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002920 // FIXME: Are these flags correct?
2921 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002922 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002923 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002924}
2925
2926/// PerformContextuallyConvertToBool - Perform a contextual conversion
2927/// of the expression From to bool (C++0x [conv]p3).
2928bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2929 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002930 if (!ICS.isBad())
2931 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002932
Fariborz Jahanian76197412009-11-18 18:26:29 +00002933 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002934 return Diag(From->getSourceRange().getBegin(),
2935 diag::err_typecheck_bool_condition)
2936 << From->getType() << From->getSourceRange();
2937 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002938}
2939
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002940/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002941/// candidate functions, using the given function call arguments. If
2942/// @p SuppressUserConversions, then don't allow user-defined
2943/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002944///
2945/// \para PartialOverloading true if we are performing "partial" overloading
2946/// based on an incomplete set of function arguments. This feature is used by
2947/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002948void
2949Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002950 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002951 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002952 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002953 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002954 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002955 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002956 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002957 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002958 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002959 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002960
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002961 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002962 if (!isa<CXXConstructorDecl>(Method)) {
2963 // If we get here, it's because we're calling a member function
2964 // that is named without a member access expression (e.g.,
2965 // "this->f") that was either written explicitly or created
2966 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002967 // function, e.g., X::f(). We use an empty type for the implied
2968 // object argument (C++ [over.call.func]p3), and the acting context
2969 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002970 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002971 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002972 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002973 return;
2974 }
2975 // We treat a constructor like a non-member function, since its object
2976 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002977 }
2978
Douglas Gregorff7028a2009-11-13 23:59:09 +00002979 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002980 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002981
Douglas Gregor27381f32009-11-23 12:27:39 +00002982 // Overload resolution is always an unevaluated context.
2983 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2984
Douglas Gregorffe14e32009-11-14 01:20:54 +00002985 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2986 // C++ [class.copy]p3:
2987 // A member function template is never instantiated to perform the copy
2988 // of a class object to an object of its class type.
2989 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2990 if (NumArgs == 1 &&
2991 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002992 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2993 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002994 return;
2995 }
2996
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002997 // Add this candidate
2998 CandidateSet.push_back(OverloadCandidate());
2999 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003000 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003001 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003002 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003003 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003004 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003005
3006 unsigned NumArgsInProto = Proto->getNumArgs();
3007
3008 // (C++ 13.3.2p2): A candidate function having fewer than m
3009 // parameters is viable only if it has an ellipsis in its parameter
3010 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003011 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3012 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003013 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003014 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003015 return;
3016 }
3017
3018 // (C++ 13.3.2p2): A candidate function having more than m parameters
3019 // is viable only if the (m+1)st parameter has a default argument
3020 // (8.3.6). For the purposes of overload resolution, the
3021 // parameter list is truncated on the right, so that there are
3022 // exactly m parameters.
3023 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003024 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003025 // Not enough arguments.
3026 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003027 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003028 return;
3029 }
3030
3031 // Determine the implicit conversion sequences for each of the
3032 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003033 Candidate.Conversions.resize(NumArgs);
3034 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3035 if (ArgIdx < NumArgsInProto) {
3036 // (C++ 13.3.2p3): for F to be a viable function, there shall
3037 // exist for each argument an implicit conversion sequence
3038 // (13.3.3.1) that converts that argument to the corresponding
3039 // parameter of F.
3040 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003041 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003042 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003043 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003044 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003045 if (Candidate.Conversions[ArgIdx].isBad()) {
3046 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003047 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003048 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003049 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003050 } else {
3051 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3052 // argument for which there is no corresponding parameter is
3053 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003054 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003055 }
3056 }
3057}
3058
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003059/// \brief Add all of the function declarations in the given function set to
3060/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003061void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003062 Expr **Args, unsigned NumArgs,
3063 OverloadCandidateSet& CandidateSet,
3064 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003065 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003066 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3067 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003068 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003069 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003070 cast<CXXMethodDecl>(FD)->getParent(),
3071 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003072 CandidateSet, SuppressUserConversions);
3073 else
John McCalla0296f72010-03-19 07:35:19 +00003074 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003075 SuppressUserConversions);
3076 } else {
John McCalla0296f72010-03-19 07:35:19 +00003077 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003078 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3079 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003080 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003081 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003082 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003083 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003084 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003085 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003086 else
John McCalla0296f72010-03-19 07:35:19 +00003087 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003088 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003089 Args, NumArgs, CandidateSet,
3090 SuppressUserConversions);
3091 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003092 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003093}
3094
John McCallf0f1cf02009-11-17 07:50:12 +00003095/// AddMethodCandidate - Adds a named decl (which is some kind of
3096/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003097void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003098 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003099 Expr **Args, unsigned NumArgs,
3100 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003101 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003102 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003103 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003104
3105 if (isa<UsingShadowDecl>(Decl))
3106 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3107
3108 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3109 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3110 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003111 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3112 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003113 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003114 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003115 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003116 } else {
John McCalla0296f72010-03-19 07:35:19 +00003117 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003118 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003119 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003120 }
3121}
3122
Douglas Gregor436424c2008-11-18 23:14:02 +00003123/// AddMethodCandidate - Adds the given C++ member function to the set
3124/// of candidate functions, using the given function call arguments
3125/// and the object argument (@c Object). For example, in a call
3126/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3127/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3128/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003129/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003130void
John McCalla0296f72010-03-19 07:35:19 +00003131Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003132 CXXRecordDecl *ActingContext, QualType ObjectType,
3133 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003134 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003135 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003136 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003137 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003138 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003139 assert(!isa<CXXConstructorDecl>(Method) &&
3140 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003141
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003142 if (!CandidateSet.isNewCandidate(Method))
3143 return;
3144
Douglas Gregor27381f32009-11-23 12:27:39 +00003145 // Overload resolution is always an unevaluated context.
3146 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3147
Douglas Gregor436424c2008-11-18 23:14:02 +00003148 // Add this candidate
3149 CandidateSet.push_back(OverloadCandidate());
3150 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003151 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003152 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003153 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003154 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003155
3156 unsigned NumArgsInProto = Proto->getNumArgs();
3157
3158 // (C++ 13.3.2p2): A candidate function having fewer than m
3159 // parameters is viable only if it has an ellipsis in its parameter
3160 // list (8.3.5).
3161 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3162 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003163 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003164 return;
3165 }
3166
3167 // (C++ 13.3.2p2): A candidate function having more than m parameters
3168 // is viable only if the (m+1)st parameter has a default argument
3169 // (8.3.6). For the purposes of overload resolution, the
3170 // parameter list is truncated on the right, so that there are
3171 // exactly m parameters.
3172 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3173 if (NumArgs < MinRequiredArgs) {
3174 // Not enough arguments.
3175 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003176 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003177 return;
3178 }
3179
3180 Candidate.Viable = true;
3181 Candidate.Conversions.resize(NumArgs + 1);
3182
John McCall6e9f8f62009-12-03 04:06:58 +00003183 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003184 // The implicit object argument is ignored.
3185 Candidate.IgnoreObjectArgument = true;
3186 else {
3187 // Determine the implicit conversion sequence for the object
3188 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003189 Candidate.Conversions[0]
3190 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003191 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003192 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003193 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003194 return;
3195 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003196 }
3197
3198 // Determine the implicit conversion sequences for each of the
3199 // arguments.
3200 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3201 if (ArgIdx < NumArgsInProto) {
3202 // (C++ 13.3.2p3): for F to be a viable function, there shall
3203 // exist for each argument an implicit conversion sequence
3204 // (13.3.3.1) that converts that argument to the corresponding
3205 // parameter of F.
3206 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003207 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003208 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003209 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003210 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003211 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003212 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003213 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003214 break;
3215 }
3216 } else {
3217 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3218 // argument for which there is no corresponding parameter is
3219 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003220 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003221 }
3222 }
3223}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003224
Douglas Gregor97628d62009-08-21 00:16:32 +00003225/// \brief Add a C++ member function template as a candidate to the candidate
3226/// set, using template argument deduction to produce an appropriate member
3227/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003228void
Douglas Gregor97628d62009-08-21 00:16:32 +00003229Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003230 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003231 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003232 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003233 QualType ObjectType,
3234 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003235 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003236 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003237 if (!CandidateSet.isNewCandidate(MethodTmpl))
3238 return;
3239
Douglas Gregor97628d62009-08-21 00:16:32 +00003240 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003241 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003242 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003243 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003244 // candidate functions in the usual way.113) A given name can refer to one
3245 // or more function templates and also to a set of overloaded non-template
3246 // functions. In such a case, the candidate functions generated from each
3247 // function template are combined with the set of non-template candidate
3248 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003249 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003250 FunctionDecl *Specialization = 0;
3251 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003252 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003253 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003254 CandidateSet.push_back(OverloadCandidate());
3255 OverloadCandidate &Candidate = CandidateSet.back();
3256 Candidate.FoundDecl = FoundDecl;
3257 Candidate.Function = MethodTmpl->getTemplatedDecl();
3258 Candidate.Viable = false;
3259 Candidate.FailureKind = ovl_fail_bad_deduction;
3260 Candidate.IsSurrogate = false;
3261 Candidate.IgnoreObjectArgument = false;
3262 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3263 Info);
3264 return;
3265 }
Mike Stump11289f42009-09-09 15:08:12 +00003266
Douglas Gregor97628d62009-08-21 00:16:32 +00003267 // Add the function template specialization produced by template argument
3268 // deduction as a candidate.
3269 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003270 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003271 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003272 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003273 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003274 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003275}
3276
Douglas Gregor05155d82009-08-21 23:19:43 +00003277/// \brief Add a C++ function template specialization as a candidate
3278/// in the candidate set, using template argument deduction to produce
3279/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003280void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003281Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003282 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003283 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003284 Expr **Args, unsigned NumArgs,
3285 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003286 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003287 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3288 return;
3289
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003290 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003291 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003292 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003293 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003294 // candidate functions in the usual way.113) A given name can refer to one
3295 // or more function templates and also to a set of overloaded non-template
3296 // functions. In such a case, the candidate functions generated from each
3297 // function template are combined with the set of non-template candidate
3298 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003299 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003300 FunctionDecl *Specialization = 0;
3301 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003302 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003303 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003304 CandidateSet.push_back(OverloadCandidate());
3305 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003306 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003307 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3308 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003309 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003310 Candidate.IsSurrogate = false;
3311 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003312 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3313 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003314 return;
3315 }
Mike Stump11289f42009-09-09 15:08:12 +00003316
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003317 // Add the function template specialization produced by template argument
3318 // deduction as a candidate.
3319 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003320 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003321 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003322}
Mike Stump11289f42009-09-09 15:08:12 +00003323
Douglas Gregora1f013e2008-11-07 22:36:19 +00003324/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003325/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003326/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003327/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003328/// (which may or may not be the same type as the type that the
3329/// conversion function produces).
3330void
3331Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003332 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003333 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003334 Expr *From, QualType ToType,
3335 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003336 assert(!Conversion->getDescribedFunctionTemplate() &&
3337 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003338 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003339 if (!CandidateSet.isNewCandidate(Conversion))
3340 return;
3341
Douglas Gregor27381f32009-11-23 12:27:39 +00003342 // Overload resolution is always an unevaluated context.
3343 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3344
Douglas Gregora1f013e2008-11-07 22:36:19 +00003345 // Add this candidate
3346 CandidateSet.push_back(OverloadCandidate());
3347 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003348 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003349 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003350 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003351 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003352 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003353 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003354 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003355
Douglas Gregor436424c2008-11-18 23:14:02 +00003356 // Determine the implicit conversion sequence for the implicit
3357 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003358 Candidate.Viable = true;
3359 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003360 Candidate.Conversions[0]
3361 = TryObjectArgumentInitialization(From->getType(), Conversion,
3362 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003363 // Conversion functions to a different type in the base class is visible in
3364 // the derived class. So, a derived to base conversion should not participate
3365 // in overload resolution.
3366 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3367 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003368 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003369 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003370 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003371 return;
3372 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003373
3374 // We won't go through a user-define type conversion function to convert a
3375 // derived to base as such conversions are given Conversion Rank. They only
3376 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3377 QualType FromCanon
3378 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3379 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3380 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3381 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003382 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003383 return;
3384 }
3385
Douglas Gregora1f013e2008-11-07 22:36:19 +00003386 // To determine what the conversion from the result of calling the
3387 // conversion function to the type we're eventually trying to
3388 // convert to (ToType), we need to synthesize a call to the
3389 // conversion function and attempt copy initialization from it. This
3390 // makes sure that we get the right semantics with respect to
3391 // lvalues/rvalues and the type. Fortunately, we can allocate this
3392 // call on the stack and we don't need its arguments to be
3393 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003394 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003395 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003396 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003397 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003398 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003399
3400 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003401 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3402 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003403 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003404 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003405 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003406 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003407 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003408 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003409 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003410
John McCall0d1da222010-01-12 00:44:57 +00003411 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003412 case ImplicitConversionSequence::StandardConversion:
3413 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003414
3415 // C++ [over.ics.user]p3:
3416 // If the user-defined conversion is specified by a specialization of a
3417 // conversion function template, the second standard conversion sequence
3418 // shall have exact match rank.
3419 if (Conversion->getPrimaryTemplate() &&
3420 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3421 Candidate.Viable = false;
3422 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3423 }
3424
Douglas Gregora1f013e2008-11-07 22:36:19 +00003425 break;
3426
3427 case ImplicitConversionSequence::BadConversion:
3428 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003429 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003430 break;
3431
3432 default:
Mike Stump11289f42009-09-09 15:08:12 +00003433 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003434 "Can only end up with a standard conversion sequence or failure");
3435 }
3436}
3437
Douglas Gregor05155d82009-08-21 23:19:43 +00003438/// \brief Adds a conversion function template specialization
3439/// candidate to the overload set, using template argument deduction
3440/// to deduce the template arguments of the conversion function
3441/// template from the type that we are converting to (C++
3442/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003443void
Douglas Gregor05155d82009-08-21 23:19:43 +00003444Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003445 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003446 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003447 Expr *From, QualType ToType,
3448 OverloadCandidateSet &CandidateSet) {
3449 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3450 "Only conversion function templates permitted here");
3451
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003452 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3453 return;
3454
John McCallbc077cf2010-02-08 23:07:23 +00003455 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003456 CXXConversionDecl *Specialization = 0;
3457 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003458 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003459 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003460 CandidateSet.push_back(OverloadCandidate());
3461 OverloadCandidate &Candidate = CandidateSet.back();
3462 Candidate.FoundDecl = FoundDecl;
3463 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3464 Candidate.Viable = false;
3465 Candidate.FailureKind = ovl_fail_bad_deduction;
3466 Candidate.IsSurrogate = false;
3467 Candidate.IgnoreObjectArgument = false;
3468 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3469 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003470 return;
3471 }
Mike Stump11289f42009-09-09 15:08:12 +00003472
Douglas Gregor05155d82009-08-21 23:19:43 +00003473 // Add the conversion function template specialization produced by
3474 // template argument deduction as a candidate.
3475 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003476 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003477 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003478}
3479
Douglas Gregorab7897a2008-11-19 22:57:39 +00003480/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3481/// converts the given @c Object to a function pointer via the
3482/// conversion function @c Conversion, and then attempts to call it
3483/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3484/// the type of function that we'll eventually be calling.
3485void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003486 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003487 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003488 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003489 QualType ObjectType,
3490 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003491 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003492 if (!CandidateSet.isNewCandidate(Conversion))
3493 return;
3494
Douglas Gregor27381f32009-11-23 12:27:39 +00003495 // Overload resolution is always an unevaluated context.
3496 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3497
Douglas Gregorab7897a2008-11-19 22:57:39 +00003498 CandidateSet.push_back(OverloadCandidate());
3499 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003500 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003501 Candidate.Function = 0;
3502 Candidate.Surrogate = Conversion;
3503 Candidate.Viable = true;
3504 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003505 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003506 Candidate.Conversions.resize(NumArgs + 1);
3507
3508 // Determine the implicit conversion sequence for the implicit
3509 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003510 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003511 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003512 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003513 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003514 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003515 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003516 return;
3517 }
3518
3519 // The first conversion is actually a user-defined conversion whose
3520 // first conversion is ObjectInit's standard conversion (which is
3521 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003522 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003523 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003524 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003525 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003526 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003527 = Candidate.Conversions[0].UserDefined.Before;
3528 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3529
Mike Stump11289f42009-09-09 15:08:12 +00003530 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003531 unsigned NumArgsInProto = Proto->getNumArgs();
3532
3533 // (C++ 13.3.2p2): A candidate function having fewer than m
3534 // parameters is viable only if it has an ellipsis in its parameter
3535 // list (8.3.5).
3536 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3537 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003538 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003539 return;
3540 }
3541
3542 // Function types don't have any default arguments, so just check if
3543 // we have enough arguments.
3544 if (NumArgs < NumArgsInProto) {
3545 // Not enough arguments.
3546 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003547 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003548 return;
3549 }
3550
3551 // Determine the implicit conversion sequences for each of the
3552 // arguments.
3553 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3554 if (ArgIdx < NumArgsInProto) {
3555 // (C++ 13.3.2p3): for F to be a viable function, there shall
3556 // exist for each argument an implicit conversion sequence
3557 // (13.3.3.1) that converts that argument to the corresponding
3558 // parameter of F.
3559 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003560 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003561 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003562 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003563 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003564 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003565 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003566 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003567 break;
3568 }
3569 } else {
3570 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3571 // argument for which there is no corresponding parameter is
3572 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003573 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003574 }
3575 }
3576}
3577
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003578/// \brief Add overload candidates for overloaded operators that are
3579/// member functions.
3580///
3581/// Add the overloaded operator candidates that are member functions
3582/// for the operator Op that was used in an operator expression such
3583/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3584/// CandidateSet will store the added overload candidates. (C++
3585/// [over.match.oper]).
3586void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3587 SourceLocation OpLoc,
3588 Expr **Args, unsigned NumArgs,
3589 OverloadCandidateSet& CandidateSet,
3590 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003591 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3592
3593 // C++ [over.match.oper]p3:
3594 // For a unary operator @ with an operand of a type whose
3595 // cv-unqualified version is T1, and for a binary operator @ with
3596 // a left operand of a type whose cv-unqualified version is T1 and
3597 // a right operand of a type whose cv-unqualified version is T2,
3598 // three sets of candidate functions, designated member
3599 // candidates, non-member candidates and built-in candidates, are
3600 // constructed as follows:
3601 QualType T1 = Args[0]->getType();
3602 QualType T2;
3603 if (NumArgs > 1)
3604 T2 = Args[1]->getType();
3605
3606 // -- If T1 is a class type, the set of member candidates is the
3607 // result of the qualified lookup of T1::operator@
3608 // (13.3.1.1.1); otherwise, the set of member candidates is
3609 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003610 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003611 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003612 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003613 return;
Mike Stump11289f42009-09-09 15:08:12 +00003614
John McCall27b18f82009-11-17 02:14:36 +00003615 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3616 LookupQualifiedName(Operators, T1Rec->getDecl());
3617 Operators.suppressDiagnostics();
3618
Mike Stump11289f42009-09-09 15:08:12 +00003619 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003620 OperEnd = Operators.end();
3621 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003622 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003623 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003624 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003625 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003626 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003627}
3628
Douglas Gregora11693b2008-11-12 17:17:38 +00003629/// AddBuiltinCandidate - Add a candidate for a built-in
3630/// operator. ResultTy and ParamTys are the result and parameter types
3631/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003632/// arguments being passed to the candidate. IsAssignmentOperator
3633/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003634/// operator. NumContextualBoolArguments is the number of arguments
3635/// (at the beginning of the argument list) that will be contextually
3636/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003637void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003638 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003639 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003640 bool IsAssignmentOperator,
3641 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003642 // Overload resolution is always an unevaluated context.
3643 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3644
Douglas Gregora11693b2008-11-12 17:17:38 +00003645 // Add this candidate
3646 CandidateSet.push_back(OverloadCandidate());
3647 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003648 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003649 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003650 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003651 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003652 Candidate.BuiltinTypes.ResultTy = ResultTy;
3653 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3654 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3655
3656 // Determine the implicit conversion sequences for each of the
3657 // arguments.
3658 Candidate.Viable = true;
3659 Candidate.Conversions.resize(NumArgs);
3660 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003661 // C++ [over.match.oper]p4:
3662 // For the built-in assignment operators, conversions of the
3663 // left operand are restricted as follows:
3664 // -- no temporaries are introduced to hold the left operand, and
3665 // -- no user-defined conversions are applied to the left
3666 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003667 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003668 //
3669 // We block these conversions by turning off user-defined
3670 // conversions, since that is the only way that initialization of
3671 // a reference to a non-class type can occur from something that
3672 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003673 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003674 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003675 "Contextual conversion to bool requires bool type");
3676 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3677 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003678 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003679 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003680 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003681 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003682 }
John McCall0d1da222010-01-12 00:44:57 +00003683 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003684 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003685 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003686 break;
3687 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003688 }
3689}
3690
3691/// BuiltinCandidateTypeSet - A set of types that will be used for the
3692/// candidate operator functions for built-in operators (C++
3693/// [over.built]). The types are separated into pointer types and
3694/// enumeration types.
3695class BuiltinCandidateTypeSet {
3696 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003697 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003698
3699 /// PointerTypes - The set of pointer types that will be used in the
3700 /// built-in candidates.
3701 TypeSet PointerTypes;
3702
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003703 /// MemberPointerTypes - The set of member pointer types that will be
3704 /// used in the built-in candidates.
3705 TypeSet MemberPointerTypes;
3706
Douglas Gregora11693b2008-11-12 17:17:38 +00003707 /// EnumerationTypes - The set of enumeration types that will be
3708 /// used in the built-in candidates.
3709 TypeSet EnumerationTypes;
3710
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003711 /// Sema - The semantic analysis instance where we are building the
3712 /// candidate type set.
3713 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003714
Douglas Gregora11693b2008-11-12 17:17:38 +00003715 /// Context - The AST context in which we will build the type sets.
3716 ASTContext &Context;
3717
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003718 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3719 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003720 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003721
3722public:
3723 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003724 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003725
Mike Stump11289f42009-09-09 15:08:12 +00003726 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003727 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003728
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003729 void AddTypesConvertedFrom(QualType Ty,
3730 SourceLocation Loc,
3731 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003732 bool AllowExplicitConversions,
3733 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003734
3735 /// pointer_begin - First pointer type found;
3736 iterator pointer_begin() { return PointerTypes.begin(); }
3737
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003738 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003739 iterator pointer_end() { return PointerTypes.end(); }
3740
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003741 /// member_pointer_begin - First member pointer type found;
3742 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3743
3744 /// member_pointer_end - Past the last member pointer type found;
3745 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3746
Douglas Gregora11693b2008-11-12 17:17:38 +00003747 /// enumeration_begin - First enumeration type found;
3748 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3749
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003750 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003751 iterator enumeration_end() { return EnumerationTypes.end(); }
3752};
3753
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003754/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003755/// the set of pointer types along with any more-qualified variants of
3756/// that type. For example, if @p Ty is "int const *", this routine
3757/// will add "int const *", "int const volatile *", "int const
3758/// restrict *", and "int const volatile restrict *" to the set of
3759/// pointer types. Returns true if the add of @p Ty itself succeeded,
3760/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003761///
3762/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003763bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003764BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3765 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003766
Douglas Gregora11693b2008-11-12 17:17:38 +00003767 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003768 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003769 return false;
3770
John McCall8ccfcb52009-09-24 19:53:00 +00003771 const PointerType *PointerTy = Ty->getAs<PointerType>();
3772 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003773
John McCall8ccfcb52009-09-24 19:53:00 +00003774 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003775 // Don't add qualified variants of arrays. For one, they're not allowed
3776 // (the qualifier would sink to the element type), and for another, the
3777 // only overload situation where it matters is subscript or pointer +- int,
3778 // and those shouldn't have qualifier variants anyway.
3779 if (PointeeTy->isArrayType())
3780 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003781 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003782 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003783 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003784 bool hasVolatile = VisibleQuals.hasVolatile();
3785 bool hasRestrict = VisibleQuals.hasRestrict();
3786
John McCall8ccfcb52009-09-24 19:53:00 +00003787 // Iterate through all strict supersets of BaseCVR.
3788 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3789 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003790 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3791 // in the types.
3792 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3793 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003794 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3795 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003796 }
3797
3798 return true;
3799}
3800
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003801/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3802/// to the set of pointer types along with any more-qualified variants of
3803/// that type. For example, if @p Ty is "int const *", this routine
3804/// will add "int const *", "int const volatile *", "int const
3805/// restrict *", and "int const volatile restrict *" to the set of
3806/// pointer types. Returns true if the add of @p Ty itself succeeded,
3807/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003808///
3809/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003810bool
3811BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3812 QualType Ty) {
3813 // Insert this type.
3814 if (!MemberPointerTypes.insert(Ty))
3815 return false;
3816
John McCall8ccfcb52009-09-24 19:53:00 +00003817 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3818 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003819
John McCall8ccfcb52009-09-24 19:53:00 +00003820 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003821 // Don't add qualified variants of arrays. For one, they're not allowed
3822 // (the qualifier would sink to the element type), and for another, the
3823 // only overload situation where it matters is subscript or pointer +- int,
3824 // and those shouldn't have qualifier variants anyway.
3825 if (PointeeTy->isArrayType())
3826 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003827 const Type *ClassTy = PointerTy->getClass();
3828
3829 // Iterate through all strict supersets of the pointee type's CVR
3830 // qualifiers.
3831 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3832 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3833 if ((CVR | BaseCVR) != CVR) continue;
3834
3835 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3836 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003837 }
3838
3839 return true;
3840}
3841
Douglas Gregora11693b2008-11-12 17:17:38 +00003842/// AddTypesConvertedFrom - Add each of the types to which the type @p
3843/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003844/// primarily interested in pointer types and enumeration types. We also
3845/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003846/// AllowUserConversions is true if we should look at the conversion
3847/// functions of a class type, and AllowExplicitConversions if we
3848/// should also include the explicit conversion functions of a class
3849/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003850void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003851BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003852 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003853 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003854 bool AllowExplicitConversions,
3855 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003856 // Only deal with canonical types.
3857 Ty = Context.getCanonicalType(Ty);
3858
3859 // Look through reference types; they aren't part of the type of an
3860 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003861 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003862 Ty = RefTy->getPointeeType();
3863
3864 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003865 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003866
Sebastian Redl65ae2002009-11-05 16:36:20 +00003867 // If we're dealing with an array type, decay to the pointer.
3868 if (Ty->isArrayType())
3869 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3870
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003871 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003872 QualType PointeeTy = PointerTy->getPointeeType();
3873
3874 // Insert our type, and its more-qualified variants, into the set
3875 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003876 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003877 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003878 } else if (Ty->isMemberPointerType()) {
3879 // Member pointers are far easier, since the pointee can't be converted.
3880 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3881 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003882 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003883 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003884 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003885 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003886 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003887 // No conversion functions in incomplete types.
3888 return;
3889 }
Mike Stump11289f42009-09-09 15:08:12 +00003890
Douglas Gregora11693b2008-11-12 17:17:38 +00003891 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003892 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003893 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003894 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003895 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003896 NamedDecl *D = I.getDecl();
3897 if (isa<UsingShadowDecl>(D))
3898 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003899
Mike Stump11289f42009-09-09 15:08:12 +00003900 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003901 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003902 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003903 continue;
3904
John McCallda4458e2010-03-31 01:36:47 +00003905 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003906 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003907 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003908 VisibleQuals);
3909 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003910 }
3911 }
3912 }
3913}
3914
Douglas Gregor84605ae2009-08-24 13:43:27 +00003915/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3916/// the volatile- and non-volatile-qualified assignment operators for the
3917/// given type to the candidate set.
3918static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3919 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003920 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003921 unsigned NumArgs,
3922 OverloadCandidateSet &CandidateSet) {
3923 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003924
Douglas Gregor84605ae2009-08-24 13:43:27 +00003925 // T& operator=(T&, T)
3926 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3927 ParamTypes[1] = T;
3928 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3929 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003930
Douglas Gregor84605ae2009-08-24 13:43:27 +00003931 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3932 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003933 ParamTypes[0]
3934 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003935 ParamTypes[1] = T;
3936 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003937 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003938 }
3939}
Mike Stump11289f42009-09-09 15:08:12 +00003940
Sebastian Redl1054fae2009-10-25 17:03:50 +00003941/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3942/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003943static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3944 Qualifiers VRQuals;
3945 const RecordType *TyRec;
3946 if (const MemberPointerType *RHSMPType =
3947 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00003948 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003949 else
3950 TyRec = ArgExpr->getType()->getAs<RecordType>();
3951 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003952 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003953 VRQuals.addVolatile();
3954 VRQuals.addRestrict();
3955 return VRQuals;
3956 }
3957
3958 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003959 if (!ClassDecl->hasDefinition())
3960 return VRQuals;
3961
John McCallad371252010-01-20 00:46:10 +00003962 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003963 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003964
John McCallad371252010-01-20 00:46:10 +00003965 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003966 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003967 NamedDecl *D = I.getDecl();
3968 if (isa<UsingShadowDecl>(D))
3969 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3970 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003971 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3972 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3973 CanTy = ResTypeRef->getPointeeType();
3974 // Need to go down the pointer/mempointer chain and add qualifiers
3975 // as see them.
3976 bool done = false;
3977 while (!done) {
3978 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3979 CanTy = ResTypePtr->getPointeeType();
3980 else if (const MemberPointerType *ResTypeMPtr =
3981 CanTy->getAs<MemberPointerType>())
3982 CanTy = ResTypeMPtr->getPointeeType();
3983 else
3984 done = true;
3985 if (CanTy.isVolatileQualified())
3986 VRQuals.addVolatile();
3987 if (CanTy.isRestrictQualified())
3988 VRQuals.addRestrict();
3989 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3990 return VRQuals;
3991 }
3992 }
3993 }
3994 return VRQuals;
3995}
3996
Douglas Gregord08452f2008-11-19 15:42:04 +00003997/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3998/// operator overloads to the candidate set (C++ [over.built]), based
3999/// on the operator @p Op and the arguments given. For example, if the
4000/// operator is a binary '+', this routine might add "int
4001/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004002void
Mike Stump11289f42009-09-09 15:08:12 +00004003Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004004 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004005 Expr **Args, unsigned NumArgs,
4006 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004007 // The set of "promoted arithmetic types", which are the arithmetic
4008 // types are that preserved by promotion (C++ [over.built]p2). Note
4009 // that the first few of these types are the promoted integral
4010 // types; these types need to be first.
4011 // FIXME: What about complex?
4012 const unsigned FirstIntegralType = 0;
4013 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004014 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004015 LastPromotedIntegralType = 13;
4016 const unsigned FirstPromotedArithmeticType = 7,
4017 LastPromotedArithmeticType = 16;
4018 const unsigned NumArithmeticTypes = 16;
4019 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004020 Context.BoolTy, Context.CharTy, Context.WCharTy,
4021// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004022 Context.SignedCharTy, Context.ShortTy,
4023 Context.UnsignedCharTy, Context.UnsignedShortTy,
4024 Context.IntTy, Context.LongTy, Context.LongLongTy,
4025 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4026 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4027 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004028 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4029 "Invalid first promoted integral type");
4030 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4031 == Context.UnsignedLongLongTy &&
4032 "Invalid last promoted integral type");
4033 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4034 "Invalid first promoted arithmetic type");
4035 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4036 == Context.LongDoubleTy &&
4037 "Invalid last promoted arithmetic type");
4038
Douglas Gregora11693b2008-11-12 17:17:38 +00004039 // Find all of the types that the arguments can convert to, but only
4040 // if the operator we're looking at has built-in operator candidates
4041 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004042 Qualifiers VisibleTypeConversionsQuals;
4043 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004044 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4045 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4046
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004047 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00004048 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
4049 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00004050 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00004051 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00004052 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00004053 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004054 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00004055 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004056 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004057 true,
4058 (Op == OO_Exclaim ||
4059 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004060 Op == OO_PipePipe),
4061 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004062 }
4063
4064 bool isComparison = false;
4065 switch (Op) {
4066 case OO_None:
4067 case NUM_OVERLOADED_OPERATORS:
4068 assert(false && "Expected an overloaded operator");
4069 break;
4070
Douglas Gregord08452f2008-11-19 15:42:04 +00004071 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004072 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004073 goto UnaryStar;
4074 else
4075 goto BinaryStar;
4076 break;
4077
4078 case OO_Plus: // '+' is either unary or binary
4079 if (NumArgs == 1)
4080 goto UnaryPlus;
4081 else
4082 goto BinaryPlus;
4083 break;
4084
4085 case OO_Minus: // '-' is either unary or binary
4086 if (NumArgs == 1)
4087 goto UnaryMinus;
4088 else
4089 goto BinaryMinus;
4090 break;
4091
4092 case OO_Amp: // '&' is either unary or binary
4093 if (NumArgs == 1)
4094 goto UnaryAmp;
4095 else
4096 goto BinaryAmp;
4097
4098 case OO_PlusPlus:
4099 case OO_MinusMinus:
4100 // C++ [over.built]p3:
4101 //
4102 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4103 // is either volatile or empty, there exist candidate operator
4104 // functions of the form
4105 //
4106 // VQ T& operator++(VQ T&);
4107 // T operator++(VQ T&, int);
4108 //
4109 // C++ [over.built]p4:
4110 //
4111 // For every pair (T, VQ), where T is an arithmetic type other
4112 // than bool, and VQ is either volatile or empty, there exist
4113 // candidate operator functions of the form
4114 //
4115 // VQ T& operator--(VQ T&);
4116 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004117 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004118 Arith < NumArithmeticTypes; ++Arith) {
4119 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004120 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004121 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004122
4123 // Non-volatile version.
4124 if (NumArgs == 1)
4125 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4126 else
4127 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004128 // heuristic to reduce number of builtin candidates in the set.
4129 // Add volatile version only if there are conversions to a volatile type.
4130 if (VisibleTypeConversionsQuals.hasVolatile()) {
4131 // Volatile version
4132 ParamTypes[0]
4133 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4134 if (NumArgs == 1)
4135 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4136 else
4137 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4138 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004139 }
4140
4141 // C++ [over.built]p5:
4142 //
4143 // For every pair (T, VQ), where T is a cv-qualified or
4144 // cv-unqualified object type, and VQ is either volatile or
4145 // empty, there exist candidate operator functions of the form
4146 //
4147 // T*VQ& operator++(T*VQ&);
4148 // T*VQ& operator--(T*VQ&);
4149 // T* operator++(T*VQ&, int);
4150 // T* operator--(T*VQ&, int);
4151 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4152 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4153 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004154 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004155 continue;
4156
Mike Stump11289f42009-09-09 15:08:12 +00004157 QualType ParamTypes[2] = {
4158 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004159 };
Mike Stump11289f42009-09-09 15:08:12 +00004160
Douglas Gregord08452f2008-11-19 15:42:04 +00004161 // Without volatile
4162 if (NumArgs == 1)
4163 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4164 else
4165 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4166
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004167 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4168 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004169 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004170 ParamTypes[0]
4171 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004172 if (NumArgs == 1)
4173 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4174 else
4175 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4176 }
4177 }
4178 break;
4179
4180 UnaryStar:
4181 // C++ [over.built]p6:
4182 // For every cv-qualified or cv-unqualified object type T, there
4183 // exist candidate operator functions of the form
4184 //
4185 // T& operator*(T*);
4186 //
4187 // C++ [over.built]p7:
4188 // For every function type T, there exist candidate operator
4189 // functions of the form
4190 // T& operator*(T*);
4191 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4192 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4193 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004194 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004195 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004196 &ParamTy, Args, 1, CandidateSet);
4197 }
4198 break;
4199
4200 UnaryPlus:
4201 // C++ [over.built]p8:
4202 // For every type T, there exist candidate operator functions of
4203 // the form
4204 //
4205 // T* operator+(T*);
4206 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4207 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4208 QualType ParamTy = *Ptr;
4209 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4210 }
Mike Stump11289f42009-09-09 15:08:12 +00004211
Douglas Gregord08452f2008-11-19 15:42:04 +00004212 // Fall through
4213
4214 UnaryMinus:
4215 // C++ [over.built]p9:
4216 // For every promoted arithmetic type T, there exist candidate
4217 // operator functions of the form
4218 //
4219 // T operator+(T);
4220 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004221 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004222 Arith < LastPromotedArithmeticType; ++Arith) {
4223 QualType ArithTy = ArithmeticTypes[Arith];
4224 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4225 }
4226 break;
4227
4228 case OO_Tilde:
4229 // C++ [over.built]p10:
4230 // For every promoted integral type T, there exist candidate
4231 // operator functions of the form
4232 //
4233 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004234 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004235 Int < LastPromotedIntegralType; ++Int) {
4236 QualType IntTy = ArithmeticTypes[Int];
4237 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4238 }
4239 break;
4240
Douglas Gregora11693b2008-11-12 17:17:38 +00004241 case OO_New:
4242 case OO_Delete:
4243 case OO_Array_New:
4244 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004245 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004246 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004247 break;
4248
4249 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004250 UnaryAmp:
4251 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004252 // C++ [over.match.oper]p3:
4253 // -- For the operator ',', the unary operator '&', or the
4254 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004255 break;
4256
Douglas Gregor84605ae2009-08-24 13:43:27 +00004257 case OO_EqualEqual:
4258 case OO_ExclaimEqual:
4259 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004260 // For every pointer to member type T, there exist candidate operator
4261 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004262 //
4263 // bool operator==(T,T);
4264 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004265 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004266 MemPtr = CandidateTypes.member_pointer_begin(),
4267 MemPtrEnd = CandidateTypes.member_pointer_end();
4268 MemPtr != MemPtrEnd;
4269 ++MemPtr) {
4270 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4271 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4272 }
Mike Stump11289f42009-09-09 15:08:12 +00004273
Douglas Gregor84605ae2009-08-24 13:43:27 +00004274 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004275
Douglas Gregora11693b2008-11-12 17:17:38 +00004276 case OO_Less:
4277 case OO_Greater:
4278 case OO_LessEqual:
4279 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004280 // C++ [over.built]p15:
4281 //
4282 // For every pointer or enumeration type T, there exist
4283 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004284 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004285 // bool operator<(T, T);
4286 // bool operator>(T, T);
4287 // bool operator<=(T, T);
4288 // bool operator>=(T, T);
4289 // bool operator==(T, T);
4290 // bool operator!=(T, T);
4291 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4292 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4293 QualType ParamTypes[2] = { *Ptr, *Ptr };
4294 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4295 }
Mike Stump11289f42009-09-09 15:08:12 +00004296 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004297 = CandidateTypes.enumeration_begin();
4298 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4299 QualType ParamTypes[2] = { *Enum, *Enum };
4300 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4301 }
4302
4303 // Fall through.
4304 isComparison = true;
4305
Douglas Gregord08452f2008-11-19 15:42:04 +00004306 BinaryPlus:
4307 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004308 if (!isComparison) {
4309 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4310
4311 // C++ [over.built]p13:
4312 //
4313 // For every cv-qualified or cv-unqualified object type T
4314 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004315 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004316 // T* operator+(T*, ptrdiff_t);
4317 // T& operator[](T*, ptrdiff_t); [BELOW]
4318 // T* operator-(T*, ptrdiff_t);
4319 // T* operator+(ptrdiff_t, T*);
4320 // T& operator[](ptrdiff_t, T*); [BELOW]
4321 //
4322 // C++ [over.built]p14:
4323 //
4324 // For every T, where T is a pointer to object type, there
4325 // exist candidate operator functions of the form
4326 //
4327 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004328 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004329 = CandidateTypes.pointer_begin();
4330 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4331 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4332
4333 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4334 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4335
4336 if (Op == OO_Plus) {
4337 // T* operator+(ptrdiff_t, T*);
4338 ParamTypes[0] = ParamTypes[1];
4339 ParamTypes[1] = *Ptr;
4340 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4341 } else {
4342 // ptrdiff_t operator-(T, T);
4343 ParamTypes[1] = *Ptr;
4344 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4345 Args, 2, CandidateSet);
4346 }
4347 }
4348 }
4349 // Fall through
4350
Douglas Gregora11693b2008-11-12 17:17:38 +00004351 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004352 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004353 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004354 // C++ [over.built]p12:
4355 //
4356 // For every pair of promoted arithmetic types L and R, there
4357 // exist candidate operator functions of the form
4358 //
4359 // LR operator*(L, R);
4360 // LR operator/(L, R);
4361 // LR operator+(L, R);
4362 // LR operator-(L, R);
4363 // bool operator<(L, R);
4364 // bool operator>(L, R);
4365 // bool operator<=(L, R);
4366 // bool operator>=(L, R);
4367 // bool operator==(L, R);
4368 // bool operator!=(L, R);
4369 //
4370 // where LR is the result of the usual arithmetic conversions
4371 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004372 //
4373 // C++ [over.built]p24:
4374 //
4375 // For every pair of promoted arithmetic types L and R, there exist
4376 // candidate operator functions of the form
4377 //
4378 // LR operator?(bool, L, R);
4379 //
4380 // where LR is the result of the usual arithmetic conversions
4381 // between types L and R.
4382 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004383 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004384 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004385 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004386 Right < LastPromotedArithmeticType; ++Right) {
4387 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004388 QualType Result
4389 = isComparison
4390 ? Context.BoolTy
4391 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004392 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4393 }
4394 }
4395 break;
4396
4397 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004398 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004399 case OO_Caret:
4400 case OO_Pipe:
4401 case OO_LessLess:
4402 case OO_GreaterGreater:
4403 // C++ [over.built]p17:
4404 //
4405 // For every pair of promoted integral types L and R, there
4406 // exist candidate operator functions of the form
4407 //
4408 // LR operator%(L, R);
4409 // LR operator&(L, R);
4410 // LR operator^(L, R);
4411 // LR operator|(L, R);
4412 // L operator<<(L, R);
4413 // L operator>>(L, R);
4414 //
4415 // where LR is the result of the usual arithmetic conversions
4416 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004417 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004418 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004419 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004420 Right < LastPromotedIntegralType; ++Right) {
4421 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4422 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4423 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004424 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004425 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4426 }
4427 }
4428 break;
4429
4430 case OO_Equal:
4431 // C++ [over.built]p20:
4432 //
4433 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004434 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004435 // empty, there exist candidate operator functions of the form
4436 //
4437 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004438 for (BuiltinCandidateTypeSet::iterator
4439 Enum = CandidateTypes.enumeration_begin(),
4440 EnumEnd = CandidateTypes.enumeration_end();
4441 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004442 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004443 CandidateSet);
4444 for (BuiltinCandidateTypeSet::iterator
4445 MemPtr = CandidateTypes.member_pointer_begin(),
4446 MemPtrEnd = CandidateTypes.member_pointer_end();
4447 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004448 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004449 CandidateSet);
4450 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004451
4452 case OO_PlusEqual:
4453 case OO_MinusEqual:
4454 // C++ [over.built]p19:
4455 //
4456 // For every pair (T, VQ), where T is any type and VQ is either
4457 // volatile or empty, there exist candidate operator functions
4458 // of the form
4459 //
4460 // T*VQ& operator=(T*VQ&, T*);
4461 //
4462 // C++ [over.built]p21:
4463 //
4464 // For every pair (T, VQ), where T is a cv-qualified or
4465 // cv-unqualified object type and VQ is either volatile or
4466 // empty, there exist candidate operator functions of the form
4467 //
4468 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4469 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4470 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4471 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4472 QualType ParamTypes[2];
4473 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4474
4475 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004476 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004477 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4478 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004479
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004480 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4481 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004482 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004483 ParamTypes[0]
4484 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004485 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4486 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004487 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004488 }
4489 // Fall through.
4490
4491 case OO_StarEqual:
4492 case OO_SlashEqual:
4493 // C++ [over.built]p18:
4494 //
4495 // For every triple (L, VQ, R), where L is an arithmetic type,
4496 // VQ is either volatile or empty, and R is a promoted
4497 // arithmetic type, there exist candidate operator functions of
4498 // the form
4499 //
4500 // VQ L& operator=(VQ L&, R);
4501 // VQ L& operator*=(VQ L&, R);
4502 // VQ L& operator/=(VQ L&, R);
4503 // VQ L& operator+=(VQ L&, R);
4504 // VQ L& operator-=(VQ L&, R);
4505 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004506 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004507 Right < LastPromotedArithmeticType; ++Right) {
4508 QualType ParamTypes[2];
4509 ParamTypes[1] = ArithmeticTypes[Right];
4510
4511 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004512 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004513 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4514 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004515
4516 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004517 if (VisibleTypeConversionsQuals.hasVolatile()) {
4518 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4519 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4520 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4521 /*IsAssigmentOperator=*/Op == OO_Equal);
4522 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004523 }
4524 }
4525 break;
4526
4527 case OO_PercentEqual:
4528 case OO_LessLessEqual:
4529 case OO_GreaterGreaterEqual:
4530 case OO_AmpEqual:
4531 case OO_CaretEqual:
4532 case OO_PipeEqual:
4533 // C++ [over.built]p22:
4534 //
4535 // For every triple (L, VQ, R), where L is an integral type, VQ
4536 // is either volatile or empty, and R is a promoted integral
4537 // type, there exist candidate operator functions of the form
4538 //
4539 // VQ L& operator%=(VQ L&, R);
4540 // VQ L& operator<<=(VQ L&, R);
4541 // VQ L& operator>>=(VQ L&, R);
4542 // VQ L& operator&=(VQ L&, R);
4543 // VQ L& operator^=(VQ L&, R);
4544 // VQ L& operator|=(VQ L&, R);
4545 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004546 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004547 Right < LastPromotedIntegralType; ++Right) {
4548 QualType ParamTypes[2];
4549 ParamTypes[1] = ArithmeticTypes[Right];
4550
4551 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004552 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004553 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004554 if (VisibleTypeConversionsQuals.hasVolatile()) {
4555 // Add this built-in operator as a candidate (VQ is 'volatile').
4556 ParamTypes[0] = ArithmeticTypes[Left];
4557 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4558 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4559 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4560 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004561 }
4562 }
4563 break;
4564
Douglas Gregord08452f2008-11-19 15:42:04 +00004565 case OO_Exclaim: {
4566 // C++ [over.operator]p23:
4567 //
4568 // There also exist candidate operator functions of the form
4569 //
Mike Stump11289f42009-09-09 15:08:12 +00004570 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004571 // bool operator&&(bool, bool); [BELOW]
4572 // bool operator||(bool, bool); [BELOW]
4573 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004574 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4575 /*IsAssignmentOperator=*/false,
4576 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004577 break;
4578 }
4579
Douglas Gregora11693b2008-11-12 17:17:38 +00004580 case OO_AmpAmp:
4581 case OO_PipePipe: {
4582 // C++ [over.operator]p23:
4583 //
4584 // There also exist candidate operator functions of the form
4585 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004586 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004587 // bool operator&&(bool, bool);
4588 // bool operator||(bool, bool);
4589 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004590 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4591 /*IsAssignmentOperator=*/false,
4592 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004593 break;
4594 }
4595
4596 case OO_Subscript:
4597 // C++ [over.built]p13:
4598 //
4599 // For every cv-qualified or cv-unqualified object type T there
4600 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004601 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004602 // T* operator+(T*, ptrdiff_t); [ABOVE]
4603 // T& operator[](T*, ptrdiff_t);
4604 // T* operator-(T*, ptrdiff_t); [ABOVE]
4605 // T* operator+(ptrdiff_t, T*); [ABOVE]
4606 // T& operator[](ptrdiff_t, T*);
4607 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4608 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4609 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004610 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004611 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004612
4613 // T& operator[](T*, ptrdiff_t)
4614 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4615
4616 // T& operator[](ptrdiff_t, T*);
4617 ParamTypes[0] = ParamTypes[1];
4618 ParamTypes[1] = *Ptr;
4619 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4620 }
4621 break;
4622
4623 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004624 // C++ [over.built]p11:
4625 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4626 // C1 is the same type as C2 or is a derived class of C2, T is an object
4627 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4628 // there exist candidate operator functions of the form
4629 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4630 // where CV12 is the union of CV1 and CV2.
4631 {
4632 for (BuiltinCandidateTypeSet::iterator Ptr =
4633 CandidateTypes.pointer_begin();
4634 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4635 QualType C1Ty = (*Ptr);
4636 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004637 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004638 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004639 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004640 if (!isa<RecordType>(C1))
4641 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004642 // heuristic to reduce number of builtin candidates in the set.
4643 // Add volatile/restrict version only if there are conversions to a
4644 // volatile/restrict type.
4645 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4646 continue;
4647 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4648 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004649 }
4650 for (BuiltinCandidateTypeSet::iterator
4651 MemPtr = CandidateTypes.member_pointer_begin(),
4652 MemPtrEnd = CandidateTypes.member_pointer_end();
4653 MemPtr != MemPtrEnd; ++MemPtr) {
4654 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4655 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004656 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004657 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4658 break;
4659 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4660 // build CV12 T&
4661 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004662 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4663 T.isVolatileQualified())
4664 continue;
4665 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4666 T.isRestrictQualified())
4667 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004668 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004669 QualType ResultTy = Context.getLValueReferenceType(T);
4670 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4671 }
4672 }
4673 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004674 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004675
4676 case OO_Conditional:
4677 // Note that we don't consider the first argument, since it has been
4678 // contextually converted to bool long ago. The candidates below are
4679 // therefore added as binary.
4680 //
4681 // C++ [over.built]p24:
4682 // For every type T, where T is a pointer or pointer-to-member type,
4683 // there exist candidate operator functions of the form
4684 //
4685 // T operator?(bool, T, T);
4686 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004687 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4688 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4689 QualType ParamTypes[2] = { *Ptr, *Ptr };
4690 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4691 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004692 for (BuiltinCandidateTypeSet::iterator Ptr =
4693 CandidateTypes.member_pointer_begin(),
4694 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4695 QualType ParamTypes[2] = { *Ptr, *Ptr };
4696 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4697 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004698 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004699 }
4700}
4701
Douglas Gregore254f902009-02-04 00:32:51 +00004702/// \brief Add function candidates found via argument-dependent lookup
4703/// to the set of overloading candidates.
4704///
4705/// This routine performs argument-dependent name lookup based on the
4706/// given function name (which may also be an operator name) and adds
4707/// all of the overload candidates found by ADL to the overload
4708/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004709void
Douglas Gregore254f902009-02-04 00:32:51 +00004710Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004711 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004712 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004713 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004714 OverloadCandidateSet& CandidateSet,
4715 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004716 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004717
John McCall91f61fc2010-01-26 06:04:06 +00004718 // FIXME: This approach for uniquing ADL results (and removing
4719 // redundant candidates from the set) relies on pointer-equality,
4720 // which means we need to key off the canonical decl. However,
4721 // always going back to the canonical decl might not get us the
4722 // right set of default arguments. What default arguments are
4723 // we supposed to consider on ADL candidates, anyway?
4724
Douglas Gregorcabea402009-09-22 15:41:20 +00004725 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004726 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004727
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004728 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004729 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4730 CandEnd = CandidateSet.end();
4731 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004732 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004733 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004734 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004735 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004736 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004737
4738 // For each of the ADL candidates we found, add it to the overload
4739 // set.
John McCall8fe68082010-01-26 07:16:45 +00004740 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004741 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004742 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004743 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004744 continue;
4745
John McCalla0296f72010-03-19 07:35:19 +00004746 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004747 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004748 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004749 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004750 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004751 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004752 }
Douglas Gregore254f902009-02-04 00:32:51 +00004753}
4754
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004755/// isBetterOverloadCandidate - Determines whether the first overload
4756/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004757bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004758Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004759 const OverloadCandidate& Cand2,
4760 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004761 // Define viable functions to be better candidates than non-viable
4762 // functions.
4763 if (!Cand2.Viable)
4764 return Cand1.Viable;
4765 else if (!Cand1.Viable)
4766 return false;
4767
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004768 // C++ [over.match.best]p1:
4769 //
4770 // -- if F is a static member function, ICS1(F) is defined such
4771 // that ICS1(F) is neither better nor worse than ICS1(G) for
4772 // any function G, and, symmetrically, ICS1(G) is neither
4773 // better nor worse than ICS1(F).
4774 unsigned StartArg = 0;
4775 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4776 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004777
Douglas Gregord3cb3562009-07-07 23:38:56 +00004778 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004779 // A viable function F1 is defined to be a better function than another
4780 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004781 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004782 unsigned NumArgs = Cand1.Conversions.size();
4783 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4784 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004785 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004786 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4787 Cand2.Conversions[ArgIdx])) {
4788 case ImplicitConversionSequence::Better:
4789 // Cand1 has a better conversion sequence.
4790 HasBetterConversion = true;
4791 break;
4792
4793 case ImplicitConversionSequence::Worse:
4794 // Cand1 can't be better than Cand2.
4795 return false;
4796
4797 case ImplicitConversionSequence::Indistinguishable:
4798 // Do nothing.
4799 break;
4800 }
4801 }
4802
Mike Stump11289f42009-09-09 15:08:12 +00004803 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004804 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004805 if (HasBetterConversion)
4806 return true;
4807
Mike Stump11289f42009-09-09 15:08:12 +00004808 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004809 // specialization, or, if not that,
4810 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4811 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4812 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004813
4814 // -- F1 and F2 are function template specializations, and the function
4815 // template for F1 is more specialized than the template for F2
4816 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004817 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004818 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4819 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004820 if (FunctionTemplateDecl *BetterTemplate
4821 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4822 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004823 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004824 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4825 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004826 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004827
Douglas Gregora1f013e2008-11-07 22:36:19 +00004828 // -- the context is an initialization by user-defined conversion
4829 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4830 // from the return type of F1 to the destination type (i.e.,
4831 // the type of the entity being initialized) is a better
4832 // conversion sequence than the standard conversion sequence
4833 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004834 if (Cand1.Function && Cand2.Function &&
4835 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004836 isa<CXXConversionDecl>(Cand2.Function)) {
4837 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4838 Cand2.FinalConversion)) {
4839 case ImplicitConversionSequence::Better:
4840 // Cand1 has a better conversion sequence.
4841 return true;
4842
4843 case ImplicitConversionSequence::Worse:
4844 // Cand1 can't be better than Cand2.
4845 return false;
4846
4847 case ImplicitConversionSequence::Indistinguishable:
4848 // Do nothing
4849 break;
4850 }
4851 }
4852
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004853 return false;
4854}
4855
Mike Stump11289f42009-09-09 15:08:12 +00004856/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004857/// within an overload candidate set.
4858///
4859/// \param CandidateSet the set of candidate functions.
4860///
4861/// \param Loc the location of the function name (or operator symbol) for
4862/// which overload resolution occurs.
4863///
Mike Stump11289f42009-09-09 15:08:12 +00004864/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004865/// function, Best points to the candidate function found.
4866///
4867/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004868OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4869 SourceLocation Loc,
4870 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004871 // Find the best viable function.
4872 Best = CandidateSet.end();
4873 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4874 Cand != CandidateSet.end(); ++Cand) {
4875 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004876 if (Best == CandidateSet.end() ||
4877 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004878 Best = Cand;
4879 }
4880 }
4881
4882 // If we didn't find any viable functions, abort.
4883 if (Best == CandidateSet.end())
4884 return OR_No_Viable_Function;
4885
4886 // Make sure that this function is better than every other viable
4887 // function. If not, we have an ambiguity.
4888 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4889 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004890 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004891 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004892 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004893 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004894 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004895 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004896 }
Mike Stump11289f42009-09-09 15:08:12 +00004897
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004898 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004899 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004900 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004901 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004902 return OR_Deleted;
4903
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004904 // C++ [basic.def.odr]p2:
4905 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004906 // when referred to from a potentially-evaluated expression. [Note: this
4907 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004908 // (clause 13), user-defined conversions (12.3.2), allocation function for
4909 // placement new (5.3.4), as well as non-default initialization (8.5).
4910 if (Best->Function)
4911 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004912 return OR_Success;
4913}
4914
John McCall53262c92010-01-12 02:15:36 +00004915namespace {
4916
4917enum OverloadCandidateKind {
4918 oc_function,
4919 oc_method,
4920 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004921 oc_function_template,
4922 oc_method_template,
4923 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004924 oc_implicit_default_constructor,
4925 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004926 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004927};
4928
John McCalle1ac8d12010-01-13 00:25:19 +00004929OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4930 FunctionDecl *Fn,
4931 std::string &Description) {
4932 bool isTemplate = false;
4933
4934 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4935 isTemplate = true;
4936 Description = S.getTemplateArgumentBindingsText(
4937 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4938 }
John McCallfd0b2f82010-01-06 09:43:14 +00004939
4940 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004941 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004942 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004943
John McCall53262c92010-01-12 02:15:36 +00004944 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4945 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004946 }
4947
4948 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4949 // This actually gets spelled 'candidate function' for now, but
4950 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004951 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004952 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004953
4954 assert(Meth->isCopyAssignment()
4955 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004956 return oc_implicit_copy_assignment;
4957 }
4958
John McCalle1ac8d12010-01-13 00:25:19 +00004959 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004960}
4961
4962} // end anonymous namespace
4963
4964// Notes the location of an overload candidate.
4965void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004966 std::string FnDesc;
4967 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4968 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4969 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004970}
4971
John McCall0d1da222010-01-12 00:44:57 +00004972/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4973/// "lead" diagnostic; it will be given two arguments, the source and
4974/// target types of the conversion.
4975void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4976 SourceLocation CaretLoc,
4977 const PartialDiagnostic &PDiag) {
4978 Diag(CaretLoc, PDiag)
4979 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4980 for (AmbiguousConversionSequence::const_iterator
4981 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4982 NoteOverloadCandidate(*I);
4983 }
John McCall12f97bc2010-01-08 04:41:39 +00004984}
4985
John McCall0d1da222010-01-12 00:44:57 +00004986namespace {
4987
John McCall6a61b522010-01-13 09:16:55 +00004988void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4989 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4990 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004991 assert(Cand->Function && "for now, candidate must be a function");
4992 FunctionDecl *Fn = Cand->Function;
4993
4994 // There's a conversion slot for the object argument if this is a
4995 // non-constructor method. Note that 'I' corresponds the
4996 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004997 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004998 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004999 if (I == 0)
5000 isObjectArgument = true;
5001 else
5002 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005003 }
5004
John McCalle1ac8d12010-01-13 00:25:19 +00005005 std::string FnDesc;
5006 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5007
John McCall6a61b522010-01-13 09:16:55 +00005008 Expr *FromExpr = Conv.Bad.FromExpr;
5009 QualType FromTy = Conv.Bad.getFromType();
5010 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005011
John McCallfb7ad0f2010-02-02 02:42:52 +00005012 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005013 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005014 Expr *E = FromExpr->IgnoreParens();
5015 if (isa<UnaryOperator>(E))
5016 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005017 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005018
5019 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5020 << (unsigned) FnKind << FnDesc
5021 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5022 << ToTy << Name << I+1;
5023 return;
5024 }
5025
John McCall6d174642010-01-23 08:10:49 +00005026 // Do some hand-waving analysis to see if the non-viability is due
5027 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005028 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5029 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5030 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5031 CToTy = RT->getPointeeType();
5032 else {
5033 // TODO: detect and diagnose the full richness of const mismatches.
5034 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5035 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5036 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5037 }
5038
5039 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5040 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5041 // It is dumb that we have to do this here.
5042 while (isa<ArrayType>(CFromTy))
5043 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5044 while (isa<ArrayType>(CToTy))
5045 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5046
5047 Qualifiers FromQs = CFromTy.getQualifiers();
5048 Qualifiers ToQs = CToTy.getQualifiers();
5049
5050 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5051 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5052 << (unsigned) FnKind << FnDesc
5053 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5054 << FromTy
5055 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5056 << (unsigned) isObjectArgument << I+1;
5057 return;
5058 }
5059
5060 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5061 assert(CVR && "unexpected qualifiers mismatch");
5062
5063 if (isObjectArgument) {
5064 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5065 << (unsigned) FnKind << FnDesc
5066 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5067 << FromTy << (CVR - 1);
5068 } else {
5069 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5070 << (unsigned) FnKind << FnDesc
5071 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5072 << FromTy << (CVR - 1) << I+1;
5073 }
5074 return;
5075 }
5076
John McCall6d174642010-01-23 08:10:49 +00005077 // Diagnose references or pointers to incomplete types differently,
5078 // since it's far from impossible that the incompleteness triggered
5079 // the failure.
5080 QualType TempFromTy = FromTy.getNonReferenceType();
5081 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5082 TempFromTy = PTy->getPointeeType();
5083 if (TempFromTy->isIncompleteType()) {
5084 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5085 << (unsigned) FnKind << FnDesc
5086 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5087 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5088 return;
5089 }
5090
John McCall47000992010-01-14 03:28:57 +00005091 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005092 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5093 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005094 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005095 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005096}
5097
5098void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5099 unsigned NumFormalArgs) {
5100 // TODO: treat calls to a missing default constructor as a special case
5101
5102 FunctionDecl *Fn = Cand->Function;
5103 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5104
5105 unsigned MinParams = Fn->getMinRequiredArguments();
5106
5107 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005108 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005109 unsigned mode, modeCount;
5110 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005111 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5112 (Cand->FailureKind == ovl_fail_bad_deduction &&
5113 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005114 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5115 mode = 0; // "at least"
5116 else
5117 mode = 2; // "exactly"
5118 modeCount = MinParams;
5119 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005120 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5121 (Cand->FailureKind == ovl_fail_bad_deduction &&
5122 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005123 if (MinParams != FnTy->getNumArgs())
5124 mode = 1; // "at most"
5125 else
5126 mode = 2; // "exactly"
5127 modeCount = FnTy->getNumArgs();
5128 }
5129
5130 std::string Description;
5131 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5132
5133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005134 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5135 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005136}
5137
John McCall8b9ed552010-02-01 18:53:26 +00005138/// Diagnose a failed template-argument deduction.
5139void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5140 Expr **Args, unsigned NumArgs) {
5141 FunctionDecl *Fn = Cand->Function; // pattern
5142
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005143 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005144 NamedDecl *ParamD;
5145 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5146 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5147 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005148 switch (Cand->DeductionFailure.Result) {
5149 case Sema::TDK_Success:
5150 llvm_unreachable("TDK_success while diagnosing bad deduction");
5151
5152 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005153 assert(ParamD && "no parameter found for incomplete deduction result");
5154 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5155 << ParamD->getDeclName();
5156 return;
5157 }
5158
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005159 case Sema::TDK_Inconsistent:
5160 case Sema::TDK_InconsistentQuals: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005161 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005162 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005163 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005164 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005165 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005166 which = 1;
5167 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005168 which = 2;
5169 }
5170
5171 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5172 << which << ParamD->getDeclName()
5173 << *Cand->DeductionFailure.getFirstArg()
5174 << *Cand->DeductionFailure.getSecondArg();
5175 return;
5176 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005177
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005178 case Sema::TDK_InvalidExplicitArguments:
5179 assert(ParamD && "no parameter found for invalid explicit arguments");
5180 if (ParamD->getDeclName())
5181 S.Diag(Fn->getLocation(),
5182 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5183 << ParamD->getDeclName();
5184 else {
5185 int index = 0;
5186 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5187 index = TTP->getIndex();
5188 else if (NonTypeTemplateParmDecl *NTTP
5189 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5190 index = NTTP->getIndex();
5191 else
5192 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5193 S.Diag(Fn->getLocation(),
5194 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5195 << (index + 1);
5196 }
5197 return;
5198
Douglas Gregor02eb4832010-05-08 18:13:28 +00005199 case Sema::TDK_TooManyArguments:
5200 case Sema::TDK_TooFewArguments:
5201 DiagnoseArityMismatch(S, Cand, NumArgs);
5202 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005203
5204 case Sema::TDK_InstantiationDepth:
5205 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5206 return;
5207
5208 case Sema::TDK_SubstitutionFailure: {
5209 std::string ArgString;
5210 if (TemplateArgumentList *Args
5211 = Cand->DeductionFailure.getTemplateArgumentList())
5212 ArgString = S.getTemplateArgumentBindingsText(
5213 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5214 *Args);
5215 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5216 << ArgString;
5217 return;
5218 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005219
John McCall8b9ed552010-02-01 18:53:26 +00005220 // TODO: diagnose these individually, then kill off
5221 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005222 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005223 case Sema::TDK_FailedOverloadResolution:
5224 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5225 return;
5226 }
5227}
5228
5229/// Generates a 'note' diagnostic for an overload candidate. We've
5230/// already generated a primary error at the call site.
5231///
5232/// It really does need to be a single diagnostic with its caret
5233/// pointed at the candidate declaration. Yes, this creates some
5234/// major challenges of technical writing. Yes, this makes pointing
5235/// out problems with specific arguments quite awkward. It's still
5236/// better than generating twenty screens of text for every failed
5237/// overload.
5238///
5239/// It would be great to be able to express per-candidate problems
5240/// more richly for those diagnostic clients that cared, but we'd
5241/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005242void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5243 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005244 FunctionDecl *Fn = Cand->Function;
5245
John McCall12f97bc2010-01-08 04:41:39 +00005246 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005247 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005248 std::string FnDesc;
5249 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005250
5251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005252 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005253 return;
John McCall12f97bc2010-01-08 04:41:39 +00005254 }
5255
John McCalle1ac8d12010-01-13 00:25:19 +00005256 // We don't really have anything else to say about viable candidates.
5257 if (Cand->Viable) {
5258 S.NoteOverloadCandidate(Fn);
5259 return;
5260 }
John McCall0d1da222010-01-12 00:44:57 +00005261
John McCall6a61b522010-01-13 09:16:55 +00005262 switch (Cand->FailureKind) {
5263 case ovl_fail_too_many_arguments:
5264 case ovl_fail_too_few_arguments:
5265 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005266
John McCall6a61b522010-01-13 09:16:55 +00005267 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005268 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5269
John McCallfe796dd2010-01-23 05:17:32 +00005270 case ovl_fail_trivial_conversion:
5271 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005272 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005273 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005274
John McCall65eb8792010-02-25 01:37:24 +00005275 case ovl_fail_bad_conversion: {
5276 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5277 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005278 if (Cand->Conversions[I].isBad())
5279 return DiagnoseBadConversion(S, Cand, I);
5280
5281 // FIXME: this currently happens when we're called from SemaInit
5282 // when user-conversion overload fails. Figure out how to handle
5283 // those conditions and diagnose them well.
5284 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005285 }
John McCall65eb8792010-02-25 01:37:24 +00005286 }
John McCalld3224162010-01-08 00:58:21 +00005287}
5288
5289void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5290 // Desugar the type of the surrogate down to a function type,
5291 // retaining as many typedefs as possible while still showing
5292 // the function type (and, therefore, its parameter types).
5293 QualType FnType = Cand->Surrogate->getConversionType();
5294 bool isLValueReference = false;
5295 bool isRValueReference = false;
5296 bool isPointer = false;
5297 if (const LValueReferenceType *FnTypeRef =
5298 FnType->getAs<LValueReferenceType>()) {
5299 FnType = FnTypeRef->getPointeeType();
5300 isLValueReference = true;
5301 } else if (const RValueReferenceType *FnTypeRef =
5302 FnType->getAs<RValueReferenceType>()) {
5303 FnType = FnTypeRef->getPointeeType();
5304 isRValueReference = true;
5305 }
5306 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5307 FnType = FnTypePtr->getPointeeType();
5308 isPointer = true;
5309 }
5310 // Desugar down to a function type.
5311 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5312 // Reconstruct the pointer/reference as appropriate.
5313 if (isPointer) FnType = S.Context.getPointerType(FnType);
5314 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5315 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5316
5317 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5318 << FnType;
5319}
5320
5321void NoteBuiltinOperatorCandidate(Sema &S,
5322 const char *Opc,
5323 SourceLocation OpLoc,
5324 OverloadCandidate *Cand) {
5325 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5326 std::string TypeStr("operator");
5327 TypeStr += Opc;
5328 TypeStr += "(";
5329 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5330 if (Cand->Conversions.size() == 1) {
5331 TypeStr += ")";
5332 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5333 } else {
5334 TypeStr += ", ";
5335 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5336 TypeStr += ")";
5337 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5338 }
5339}
5340
5341void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5342 OverloadCandidate *Cand) {
5343 unsigned NoOperands = Cand->Conversions.size();
5344 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5345 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005346 if (ICS.isBad()) break; // all meaningless after first invalid
5347 if (!ICS.isAmbiguous()) continue;
5348
5349 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005350 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005351 }
5352}
5353
John McCall3712d9e2010-01-15 23:32:50 +00005354SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5355 if (Cand->Function)
5356 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005357 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005358 return Cand->Surrogate->getLocation();
5359 return SourceLocation();
5360}
5361
John McCallad2587a2010-01-12 00:48:53 +00005362struct CompareOverloadCandidatesForDisplay {
5363 Sema &S;
5364 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005365
5366 bool operator()(const OverloadCandidate *L,
5367 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005368 // Fast-path this check.
5369 if (L == R) return false;
5370
John McCall12f97bc2010-01-08 04:41:39 +00005371 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005372 if (L->Viable) {
5373 if (!R->Viable) return true;
5374
5375 // TODO: introduce a tri-valued comparison for overload
5376 // candidates. Would be more worthwhile if we had a sort
5377 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005378 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5379 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005380 } else if (R->Viable)
5381 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005382
John McCall3712d9e2010-01-15 23:32:50 +00005383 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005384
John McCall3712d9e2010-01-15 23:32:50 +00005385 // Criteria by which we can sort non-viable candidates:
5386 if (!L->Viable) {
5387 // 1. Arity mismatches come after other candidates.
5388 if (L->FailureKind == ovl_fail_too_many_arguments ||
5389 L->FailureKind == ovl_fail_too_few_arguments)
5390 return false;
5391 if (R->FailureKind == ovl_fail_too_many_arguments ||
5392 R->FailureKind == ovl_fail_too_few_arguments)
5393 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005394
John McCallfe796dd2010-01-23 05:17:32 +00005395 // 2. Bad conversions come first and are ordered by the number
5396 // of bad conversions and quality of good conversions.
5397 if (L->FailureKind == ovl_fail_bad_conversion) {
5398 if (R->FailureKind != ovl_fail_bad_conversion)
5399 return true;
5400
5401 // If there's any ordering between the defined conversions...
5402 // FIXME: this might not be transitive.
5403 assert(L->Conversions.size() == R->Conversions.size());
5404
5405 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005406 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5407 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005408 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5409 R->Conversions[I])) {
5410 case ImplicitConversionSequence::Better:
5411 leftBetter++;
5412 break;
5413
5414 case ImplicitConversionSequence::Worse:
5415 leftBetter--;
5416 break;
5417
5418 case ImplicitConversionSequence::Indistinguishable:
5419 break;
5420 }
5421 }
5422 if (leftBetter > 0) return true;
5423 if (leftBetter < 0) return false;
5424
5425 } else if (R->FailureKind == ovl_fail_bad_conversion)
5426 return false;
5427
John McCall3712d9e2010-01-15 23:32:50 +00005428 // TODO: others?
5429 }
5430
5431 // Sort everything else by location.
5432 SourceLocation LLoc = GetLocationForCandidate(L);
5433 SourceLocation RLoc = GetLocationForCandidate(R);
5434
5435 // Put candidates without locations (e.g. builtins) at the end.
5436 if (LLoc.isInvalid()) return false;
5437 if (RLoc.isInvalid()) return true;
5438
5439 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005440 }
5441};
5442
John McCallfe796dd2010-01-23 05:17:32 +00005443/// CompleteNonViableCandidate - Normally, overload resolution only
5444/// computes up to the first
5445void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5446 Expr **Args, unsigned NumArgs) {
5447 assert(!Cand->Viable);
5448
5449 // Don't do anything on failures other than bad conversion.
5450 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5451
5452 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005453 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005454 unsigned ConvCount = Cand->Conversions.size();
5455 while (true) {
5456 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5457 ConvIdx++;
5458 if (Cand->Conversions[ConvIdx - 1].isBad())
5459 break;
5460 }
5461
5462 if (ConvIdx == ConvCount)
5463 return;
5464
John McCall65eb8792010-02-25 01:37:24 +00005465 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5466 "remaining conversion is initialized?");
5467
Douglas Gregoradc7a702010-04-16 17:45:54 +00005468 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005469 // operation somehow.
5470 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005471
5472 const FunctionProtoType* Proto;
5473 unsigned ArgIdx = ConvIdx;
5474
5475 if (Cand->IsSurrogate) {
5476 QualType ConvType
5477 = Cand->Surrogate->getConversionType().getNonReferenceType();
5478 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5479 ConvType = ConvPtrType->getPointeeType();
5480 Proto = ConvType->getAs<FunctionProtoType>();
5481 ArgIdx--;
5482 } else if (Cand->Function) {
5483 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5484 if (isa<CXXMethodDecl>(Cand->Function) &&
5485 !isa<CXXConstructorDecl>(Cand->Function))
5486 ArgIdx--;
5487 } else {
5488 // Builtin binary operator with a bad first conversion.
5489 assert(ConvCount <= 3);
5490 for (; ConvIdx != ConvCount; ++ConvIdx)
5491 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005492 = TryCopyInitialization(S, Args[ConvIdx],
5493 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5494 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005495 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005496 return;
5497 }
5498
5499 // Fill in the rest of the conversions.
5500 unsigned NumArgsInProto = Proto->getNumArgs();
5501 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5502 if (ArgIdx < NumArgsInProto)
5503 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005504 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5505 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005506 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005507 else
5508 Cand->Conversions[ConvIdx].setEllipsis();
5509 }
5510}
5511
John McCalld3224162010-01-08 00:58:21 +00005512} // end anonymous namespace
5513
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005514/// PrintOverloadCandidates - When overload resolution fails, prints
5515/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005516/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005517void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005518Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005519 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005520 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005521 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005522 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005523 // Sort the candidates by viability and position. Sorting directly would
5524 // be prohibitive, so we make a set of pointers and sort those.
5525 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5526 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5527 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5528 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005529 Cand != LastCand; ++Cand) {
5530 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005531 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005532 else if (OCD == OCD_AllCandidates) {
5533 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5534 Cands.push_back(Cand);
5535 }
5536 }
5537
John McCallad2587a2010-01-12 00:48:53 +00005538 std::sort(Cands.begin(), Cands.end(),
5539 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005540
John McCall0d1da222010-01-12 00:44:57 +00005541 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005542
John McCall12f97bc2010-01-08 04:41:39 +00005543 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5544 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5545 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005546
John McCalld3224162010-01-08 00:58:21 +00005547 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005548 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005549 else if (Cand->IsSurrogate)
5550 NoteSurrogateCandidate(*this, Cand);
5551
5552 // This a builtin candidate. We do not, in general, want to list
5553 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005554 else if (Cand->Viable) {
5555 // Generally we only see ambiguities including viable builtin
5556 // operators if overload resolution got screwed up by an
5557 // ambiguous user-defined conversion.
5558 //
5559 // FIXME: It's quite possible for different conversions to see
5560 // different ambiguities, though.
5561 if (!ReportedAmbiguousConversions) {
5562 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5563 ReportedAmbiguousConversions = true;
5564 }
John McCalld3224162010-01-08 00:58:21 +00005565
John McCall0d1da222010-01-12 00:44:57 +00005566 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005567 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005568 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005569 }
5570}
5571
John McCalla0296f72010-03-19 07:35:19 +00005572static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005573 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005574 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005575
John McCalla0296f72010-03-19 07:35:19 +00005576 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005577}
5578
Douglas Gregorcd695e52008-11-10 20:40:00 +00005579/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5580/// an overloaded function (C++ [over.over]), where @p From is an
5581/// expression with overloaded function type and @p ToType is the type
5582/// we're trying to resolve to. For example:
5583///
5584/// @code
5585/// int f(double);
5586/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005587///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005588/// int (*pfd)(double) = f; // selects f(double)
5589/// @endcode
5590///
5591/// This routine returns the resulting FunctionDecl if it could be
5592/// resolved, and NULL otherwise. When @p Complain is true, this
5593/// routine will emit diagnostics if there is an error.
5594FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005595Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005596 bool Complain,
5597 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005598 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005599 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005600 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005601 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005602 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005603 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005604 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005605 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005606 FunctionType = MemTypePtr->getPointeeType();
5607 IsMember = true;
5608 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005609
Douglas Gregorcd695e52008-11-10 20:40:00 +00005610 // C++ [over.over]p1:
5611 // [...] [Note: any redundant set of parentheses surrounding the
5612 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005613 // C++ [over.over]p1:
5614 // [...] The overloaded function name can be preceded by the &
5615 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005616 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5617 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5618 if (OvlExpr->hasExplicitTemplateArgs()) {
5619 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5620 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005621 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005622
5623 // We expect a pointer or reference to function, or a function pointer.
5624 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5625 if (!FunctionType->isFunctionType()) {
5626 if (Complain)
5627 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5628 << OvlExpr->getName() << ToType;
5629
5630 return 0;
5631 }
5632
5633 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005634
Douglas Gregorcd695e52008-11-10 20:40:00 +00005635 // Look through all of the overloaded functions, searching for one
5636 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005637 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005638 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5639
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005640 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005641 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5642 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005643 // Look through any using declarations to find the underlying function.
5644 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5645
Douglas Gregorcd695e52008-11-10 20:40:00 +00005646 // C++ [over.over]p3:
5647 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005648 // targets of type "pointer-to-function" or "reference-to-function."
5649 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005650 // type "pointer-to-member-function."
5651 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005652
Mike Stump11289f42009-09-09 15:08:12 +00005653 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005654 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005655 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005656 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005657 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005658 // static when converting to member pointer.
5659 if (Method->isStatic() == IsMember)
5660 continue;
5661 } else if (IsMember)
5662 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005663
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005664 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005665 // If the name is a function template, template argument deduction is
5666 // done (14.8.2.2), and if the argument deduction succeeds, the
5667 // resulting template argument list is used to generate a single
5668 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005669 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005670 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005671 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005672 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005673 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005674 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005675 FunctionType, Specialization, Info)) {
5676 // FIXME: make a note of the failed deduction for diagnostics.
5677 (void)Result;
5678 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005679 // FIXME: If the match isn't exact, shouldn't we just drop this as
5680 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005681 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005682 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005683 Matches.push_back(std::make_pair(I.getPair(),
5684 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005685 }
John McCalld14a8642009-11-21 08:51:07 +00005686
5687 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005688 }
Mike Stump11289f42009-09-09 15:08:12 +00005689
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005691 // Skip non-static functions when converting to pointer, and static
5692 // when converting to member pointer.
5693 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005694 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005695
5696 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005697 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005698 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005699 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005700 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005701
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005702 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005703 QualType ResultTy;
5704 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5705 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5706 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005707 Matches.push_back(std::make_pair(I.getPair(),
5708 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005709 FoundNonTemplateFunction = true;
5710 }
Mike Stump11289f42009-09-09 15:08:12 +00005711 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005712 }
5713
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005714 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005715 if (Matches.empty()) {
5716 if (Complain) {
5717 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5718 << OvlExpr->getName() << FunctionType;
5719 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5720 E = OvlExpr->decls_end();
5721 I != E; ++I)
5722 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5723 NoteOverloadCandidate(F);
5724 }
5725
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005726 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005727 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005728 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005729 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005730 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005731 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005732 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005733 return Result;
5734 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005735
5736 // C++ [over.over]p4:
5737 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005738 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005739 // [...] and any given function template specialization F1 is
5740 // eliminated if the set contains a second function template
5741 // specialization whose function template is more specialized
5742 // than the function template of F1 according to the partial
5743 // ordering rules of 14.5.5.2.
5744
5745 // The algorithm specified above is quadratic. We instead use a
5746 // two-pass algorithm (similar to the one used to identify the
5747 // best viable function in an overload set) that identifies the
5748 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005749
5750 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5751 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5752 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005753
5754 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005755 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005756 TPOC_Other, From->getLocStart(),
5757 PDiag(),
5758 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005759 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005760 PDiag(diag::note_ovl_candidate)
5761 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005762 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005763 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005764 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005765 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00005766 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00005767 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5768 }
John McCall58cc69d2010-01-27 01:50:18 +00005769 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005770 }
Mike Stump11289f42009-09-09 15:08:12 +00005771
Douglas Gregorfae1d712009-09-26 03:56:17 +00005772 // [...] any function template specializations in the set are
5773 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005774 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005775 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005776 ++I;
5777 else {
John McCalla0296f72010-03-19 07:35:19 +00005778 Matches[I] = Matches[--N];
5779 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005780 }
5781 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005782
Mike Stump11289f42009-09-09 15:08:12 +00005783 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005784 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005785 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005786 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005787 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005788 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00005789 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00005790 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5791 }
John McCalla0296f72010-03-19 07:35:19 +00005792 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005793 }
Mike Stump11289f42009-09-09 15:08:12 +00005794
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005795 // FIXME: We should probably return the same thing that BestViableFunction
5796 // returns (even if we issue the diagnostics here).
5797 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005798 << Matches[0].second->getDeclName();
5799 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5800 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005801 return 0;
5802}
5803
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005804/// \brief Given an expression that refers to an overloaded function, try to
5805/// resolve that overloaded function expression down to a single function.
5806///
5807/// This routine can only resolve template-ids that refer to a single function
5808/// template, where that template-id refers to a single template whose template
5809/// arguments are either provided by the template-id or have defaults,
5810/// as described in C++0x [temp.arg.explicit]p3.
5811FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5812 // C++ [over.over]p1:
5813 // [...] [Note: any redundant set of parentheses surrounding the
5814 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005815 // C++ [over.over]p1:
5816 // [...] The overloaded function name can be preceded by the &
5817 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005818
5819 if (From->getType() != Context.OverloadTy)
5820 return 0;
5821
5822 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005823
5824 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005825 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005826 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005827
5828 TemplateArgumentListInfo ExplicitTemplateArgs;
5829 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005830
5831 // Look through all of the overloaded functions, searching for one
5832 // whose type matches exactly.
5833 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005834 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5835 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005836 // C++0x [temp.arg.explicit]p3:
5837 // [...] In contexts where deduction is done and fails, or in contexts
5838 // where deduction is not done, if a template argument list is
5839 // specified and it, along with any default template arguments,
5840 // identifies a single function template specialization, then the
5841 // template-id is an lvalue for the function template specialization.
5842 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5843
5844 // C++ [over.over]p2:
5845 // If the name is a function template, template argument deduction is
5846 // done (14.8.2.2), and if the argument deduction succeeds, the
5847 // resulting template argument list is used to generate a single
5848 // function template specialization, which is added to the set of
5849 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005850 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005851 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005852 if (TemplateDeductionResult Result
5853 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5854 Specialization, Info)) {
5855 // FIXME: make a note of the failed deduction for diagnostics.
5856 (void)Result;
5857 continue;
5858 }
5859
5860 // Multiple matches; we can't resolve to a single declaration.
5861 if (Matched)
5862 return 0;
5863
5864 Matched = Specialization;
5865 }
5866
5867 return Matched;
5868}
5869
Douglas Gregorcabea402009-09-22 15:41:20 +00005870/// \brief Add a single candidate to the overload set.
5871static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005872 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005873 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005874 Expr **Args, unsigned NumArgs,
5875 OverloadCandidateSet &CandidateSet,
5876 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005877 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005878 if (isa<UsingShadowDecl>(Callee))
5879 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5880
Douglas Gregorcabea402009-09-22 15:41:20 +00005881 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005882 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005883 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005884 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005885 return;
John McCalld14a8642009-11-21 08:51:07 +00005886 }
5887
5888 if (FunctionTemplateDecl *FuncTemplate
5889 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005890 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5891 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005892 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005893 return;
5894 }
5895
5896 assert(false && "unhandled case in overloaded call candidate");
5897
5898 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005899}
5900
5901/// \brief Add the overload candidates named by callee and/or found by argument
5902/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005903void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005904 Expr **Args, unsigned NumArgs,
5905 OverloadCandidateSet &CandidateSet,
5906 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005907
5908#ifndef NDEBUG
5909 // Verify that ArgumentDependentLookup is consistent with the rules
5910 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005911 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005912 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5913 // and let Y be the lookup set produced by argument dependent
5914 // lookup (defined as follows). If X contains
5915 //
5916 // -- a declaration of a class member, or
5917 //
5918 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005919 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005920 //
5921 // -- a declaration that is neither a function or a function
5922 // template
5923 //
5924 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005925
John McCall57500772009-12-16 12:17:52 +00005926 if (ULE->requiresADL()) {
5927 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5928 E = ULE->decls_end(); I != E; ++I) {
5929 assert(!(*I)->getDeclContext()->isRecord());
5930 assert(isa<UsingShadowDecl>(*I) ||
5931 !(*I)->getDeclContext()->isFunctionOrMethod());
5932 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005933 }
5934 }
5935#endif
5936
John McCall57500772009-12-16 12:17:52 +00005937 // It would be nice to avoid this copy.
5938 TemplateArgumentListInfo TABuffer;
5939 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5940 if (ULE->hasExplicitTemplateArgs()) {
5941 ULE->copyTemplateArgumentsInto(TABuffer);
5942 ExplicitTemplateArgs = &TABuffer;
5943 }
5944
5945 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5946 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005947 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005948 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005949 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005950
John McCall57500772009-12-16 12:17:52 +00005951 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005952 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5953 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005954 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005955 CandidateSet,
5956 PartialOverloading);
5957}
John McCalld681c392009-12-16 08:11:27 +00005958
John McCall57500772009-12-16 12:17:52 +00005959static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5960 Expr **Args, unsigned NumArgs) {
5961 Fn->Destroy(SemaRef.Context);
5962 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5963 Args[Arg]->Destroy(SemaRef.Context);
5964 return SemaRef.ExprError();
5965}
5966
John McCalld681c392009-12-16 08:11:27 +00005967/// Attempts to recover from a call where no functions were found.
5968///
5969/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005970static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005971BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005972 UnresolvedLookupExpr *ULE,
5973 SourceLocation LParenLoc,
5974 Expr **Args, unsigned NumArgs,
5975 SourceLocation *CommaLocs,
5976 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005977
5978 CXXScopeSpec SS;
5979 if (ULE->getQualifier()) {
5980 SS.setScopeRep(ULE->getQualifier());
5981 SS.setRange(ULE->getQualifierRange());
5982 }
5983
John McCall57500772009-12-16 12:17:52 +00005984 TemplateArgumentListInfo TABuffer;
5985 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5986 if (ULE->hasExplicitTemplateArgs()) {
5987 ULE->copyTemplateArgumentsInto(TABuffer);
5988 ExplicitTemplateArgs = &TABuffer;
5989 }
5990
John McCalld681c392009-12-16 08:11:27 +00005991 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5992 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005993 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005994 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005995
John McCall57500772009-12-16 12:17:52 +00005996 assert(!R.empty() && "lookup results empty despite recovery");
5997
5998 // Build an implicit member call if appropriate. Just drop the
5999 // casts and such from the call, we don't really care.
6000 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6001 if ((*R.begin())->isCXXClassMember())
6002 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6003 else if (ExplicitTemplateArgs)
6004 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6005 else
6006 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6007
6008 if (NewFn.isInvalid())
6009 return Destroy(SemaRef, Fn, Args, NumArgs);
6010
6011 Fn->Destroy(SemaRef.Context);
6012
6013 // This shouldn't cause an infinite loop because we're giving it
6014 // an expression with non-empty lookup results, which should never
6015 // end up here.
6016 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6017 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6018 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006019}
Douglas Gregorcabea402009-09-22 15:41:20 +00006020
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006021/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006022/// (which eventually refers to the declaration Func) and the call
6023/// arguments Args/NumArgs, attempt to resolve the function call down
6024/// to a specific function. If overload resolution succeeds, returns
6025/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006026/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006027/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006028Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006029Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006030 SourceLocation LParenLoc,
6031 Expr **Args, unsigned NumArgs,
6032 SourceLocation *CommaLocs,
6033 SourceLocation RParenLoc) {
6034#ifndef NDEBUG
6035 if (ULE->requiresADL()) {
6036 // To do ADL, we must have found an unqualified name.
6037 assert(!ULE->getQualifier() && "qualified name with ADL");
6038
6039 // We don't perform ADL for implicit declarations of builtins.
6040 // Verify that this was correctly set up.
6041 FunctionDecl *F;
6042 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6043 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6044 F->getBuiltinID() && F->isImplicit())
6045 assert(0 && "performing ADL for builtin");
6046
6047 // We don't perform ADL in C.
6048 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6049 }
6050#endif
6051
John McCallbc077cf2010-02-08 23:07:23 +00006052 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006053
John McCall57500772009-12-16 12:17:52 +00006054 // Add the functions denoted by the callee to the set of candidate
6055 // functions, including those from argument-dependent lookup.
6056 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006057
6058 // If we found nothing, try to recover.
6059 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6060 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006061 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006062 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006063 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006064
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006065 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006066 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006067 case OR_Success: {
6068 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006069 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006070 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006071 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006072 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6073 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006074
6075 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006076 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006077 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006078 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006079 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006080 break;
6081
6082 case OR_Ambiguous:
6083 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006084 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006085 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006086 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006087
6088 case OR_Deleted:
6089 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6090 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006091 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006092 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006093 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006094 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006095 }
6096
6097 // Overload resolution failed. Destroy all of the subexpressions and
6098 // return NULL.
6099 Fn->Destroy(Context);
6100 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6101 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00006102 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006103}
6104
John McCall4c4c1df2010-01-26 03:27:55 +00006105static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006106 return Functions.size() > 1 ||
6107 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6108}
6109
Douglas Gregor084d8552009-03-13 23:49:33 +00006110/// \brief Create a unary operation that may resolve to an overloaded
6111/// operator.
6112///
6113/// \param OpLoc The location of the operator itself (e.g., '*').
6114///
6115/// \param OpcIn The UnaryOperator::Opcode that describes this
6116/// operator.
6117///
6118/// \param Functions The set of non-member functions that will be
6119/// considered by overload resolution. The caller needs to build this
6120/// set based on the context using, e.g.,
6121/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6122/// set should not contain any member functions; those will be added
6123/// by CreateOverloadedUnaryOp().
6124///
6125/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006126Sema::OwningExprResult
6127Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6128 const UnresolvedSetImpl &Fns,
6129 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006130 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6131 Expr *Input = (Expr *)input.get();
6132
6133 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6134 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6135 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6136
6137 Expr *Args[2] = { Input, 0 };
6138 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006139
Douglas Gregor084d8552009-03-13 23:49:33 +00006140 // For post-increment and post-decrement, add the implicit '0' as
6141 // the second argument, so that we know this is a post-increment or
6142 // post-decrement.
6143 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6144 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006145 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006146 SourceLocation());
6147 NumArgs = 2;
6148 }
6149
6150 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00006151 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006152 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006153 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006154 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006155 /*ADL*/ true, IsOverloaded(Fns));
6156 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00006157
Douglas Gregor084d8552009-03-13 23:49:33 +00006158 input.release();
6159 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6160 &Args[0], NumArgs,
6161 Context.DependentTy,
6162 OpLoc));
6163 }
6164
6165 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006166 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006167
6168 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006169 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006170
6171 // Add operator candidates that are member functions.
6172 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6173
John McCall4c4c1df2010-01-26 03:27:55 +00006174 // Add candidates from ADL.
6175 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006176 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006177 /*ExplicitTemplateArgs*/ 0,
6178 CandidateSet);
6179
Douglas Gregor084d8552009-03-13 23:49:33 +00006180 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006181 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006182
6183 // Perform overload resolution.
6184 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006185 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006186 case OR_Success: {
6187 // We found a built-in operator or an overloaded operator.
6188 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006189
Douglas Gregor084d8552009-03-13 23:49:33 +00006190 if (FnDecl) {
6191 // We matched an overloaded operator. Build a call to that
6192 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006193
Douglas Gregor084d8552009-03-13 23:49:33 +00006194 // Convert the arguments.
6195 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006196 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006197
John McCall16df1e52010-03-30 21:47:33 +00006198 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6199 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006200 return ExprError();
6201 } else {
6202 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006203 OwningExprResult InputInit
6204 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006205 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006206 SourceLocation(),
6207 move(input));
6208 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006209 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006210
Douglas Gregore6600372009-12-23 17:40:29 +00006211 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006212 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006213 }
6214
John McCall4fa0d5f2010-05-06 18:15:07 +00006215 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6216
Douglas Gregor084d8552009-03-13 23:49:33 +00006217 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006218 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006219
Douglas Gregor084d8552009-03-13 23:49:33 +00006220 // Build the actual expression node.
6221 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6222 SourceLocation());
6223 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006224
Douglas Gregor084d8552009-03-13 23:49:33 +00006225 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006226 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006227 ExprOwningPtr<CallExpr> TheCall(this,
6228 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006229 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006230
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006231 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6232 FnDecl))
6233 return ExprError();
6234
6235 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006236 } else {
6237 // We matched a built-in operator. Convert the arguments, then
6238 // break out so that we will build the appropriate built-in
6239 // operator node.
6240 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006241 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006242 return ExprError();
6243
6244 break;
6245 }
6246 }
6247
6248 case OR_No_Viable_Function:
6249 // No viable function; fall through to handling this as a
6250 // built-in operator, which will produce an error message for us.
6251 break;
6252
6253 case OR_Ambiguous:
6254 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6255 << UnaryOperator::getOpcodeStr(Opc)
6256 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006257 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006258 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006259 return ExprError();
6260
6261 case OR_Deleted:
6262 Diag(OpLoc, diag::err_ovl_deleted_oper)
6263 << Best->Function->isDeleted()
6264 << UnaryOperator::getOpcodeStr(Opc)
6265 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006266 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006267 return ExprError();
6268 }
6269
6270 // Either we found no viable overloaded operator or we matched a
6271 // built-in operator. In either case, fall through to trying to
6272 // build a built-in operation.
6273 input.release();
6274 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6275}
6276
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006277/// \brief Create a binary operation that may resolve to an overloaded
6278/// operator.
6279///
6280/// \param OpLoc The location of the operator itself (e.g., '+').
6281///
6282/// \param OpcIn The BinaryOperator::Opcode that describes this
6283/// operator.
6284///
6285/// \param Functions The set of non-member functions that will be
6286/// considered by overload resolution. The caller needs to build this
6287/// set based on the context using, e.g.,
6288/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6289/// set should not contain any member functions; those will be added
6290/// by CreateOverloadedBinOp().
6291///
6292/// \param LHS Left-hand argument.
6293/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006294Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006295Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006296 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006297 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006298 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006299 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006300 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006301
6302 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6303 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6304 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6305
6306 // If either side is type-dependent, create an appropriate dependent
6307 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006308 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006309 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006310 // If there are no functions to store, just build a dependent
6311 // BinaryOperator or CompoundAssignment.
6312 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6313 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6314 Context.DependentTy, OpLoc));
6315
6316 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6317 Context.DependentTy,
6318 Context.DependentTy,
6319 Context.DependentTy,
6320 OpLoc));
6321 }
John McCall4c4c1df2010-01-26 03:27:55 +00006322
6323 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006324 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006325 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006326 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006327 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006328 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006329
John McCall4c4c1df2010-01-26 03:27:55 +00006330 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006331 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006332 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006333 Context.DependentTy,
6334 OpLoc));
6335 }
6336
6337 // If this is the .* operator, which is not overloadable, just
6338 // create a built-in binary operator.
6339 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006340 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006341
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006342 // If this is the assignment operator, we only perform overload resolution
6343 // if the left-hand side is a class or enumeration type. This is actually
6344 // a hack. The standard requires that we do overload resolution between the
6345 // various built-in candidates, but as DR507 points out, this can lead to
6346 // problems. So we do it this way, which pretty much follows what GCC does.
6347 // Note that we go the traditional code path for compound assignment forms.
6348 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006349 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006350
Douglas Gregor084d8552009-03-13 23:49:33 +00006351 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006352 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006353
6354 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006355 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006356
6357 // Add operator candidates that are member functions.
6358 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6359
John McCall4c4c1df2010-01-26 03:27:55 +00006360 // Add candidates from ADL.
6361 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6362 Args, 2,
6363 /*ExplicitTemplateArgs*/ 0,
6364 CandidateSet);
6365
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006366 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006367 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006368
6369 // Perform overload resolution.
6370 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006371 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006372 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006373 // We found a built-in operator or an overloaded operator.
6374 FunctionDecl *FnDecl = Best->Function;
6375
6376 if (FnDecl) {
6377 // We matched an overloaded operator. Build a call to that
6378 // operator.
6379
6380 // Convert the arguments.
6381 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006382 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006383 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006384
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006385 OwningExprResult Arg1
6386 = PerformCopyInitialization(
6387 InitializedEntity::InitializeParameter(
6388 FnDecl->getParamDecl(0)),
6389 SourceLocation(),
6390 Owned(Args[1]));
6391 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006392 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006393
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006394 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006395 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006396 return ExprError();
6397
6398 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006399 } else {
6400 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006401 OwningExprResult Arg0
6402 = PerformCopyInitialization(
6403 InitializedEntity::InitializeParameter(
6404 FnDecl->getParamDecl(0)),
6405 SourceLocation(),
6406 Owned(Args[0]));
6407 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006408 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006409
6410 OwningExprResult Arg1
6411 = PerformCopyInitialization(
6412 InitializedEntity::InitializeParameter(
6413 FnDecl->getParamDecl(1)),
6414 SourceLocation(),
6415 Owned(Args[1]));
6416 if (Arg1.isInvalid())
6417 return ExprError();
6418 Args[0] = LHS = Arg0.takeAs<Expr>();
6419 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006420 }
6421
John McCall4fa0d5f2010-05-06 18:15:07 +00006422 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6423
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006424 // Determine the result type
6425 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006426 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006427 ResultTy = ResultTy.getNonReferenceType();
6428
6429 // Build the actual expression node.
6430 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006431 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006432 UsualUnaryConversions(FnExpr);
6433
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006434 ExprOwningPtr<CXXOperatorCallExpr>
6435 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6436 Args, 2, ResultTy,
6437 OpLoc));
6438
6439 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6440 FnDecl))
6441 return ExprError();
6442
6443 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006444 } else {
6445 // We matched a built-in operator. Convert the arguments, then
6446 // break out so that we will build the appropriate built-in
6447 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006448 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006449 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006450 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006451 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006452 return ExprError();
6453
6454 break;
6455 }
6456 }
6457
Douglas Gregor66950a32009-09-30 21:46:01 +00006458 case OR_No_Viable_Function: {
6459 // C++ [over.match.oper]p9:
6460 // If the operator is the operator , [...] and there are no
6461 // viable functions, then the operator is assumed to be the
6462 // built-in operator and interpreted according to clause 5.
6463 if (Opc == BinaryOperator::Comma)
6464 break;
6465
Sebastian Redl027de2a2009-05-21 11:50:50 +00006466 // For class as left operand for assignment or compound assigment operator
6467 // do not fall through to handling in built-in, but report that no overloaded
6468 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006469 OwningExprResult Result = ExprError();
6470 if (Args[0]->getType()->isRecordType() &&
6471 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006472 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6473 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006474 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006475 } else {
6476 // No viable function; try to create a built-in operation, which will
6477 // produce an error. Then, show the non-viable candidates.
6478 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006479 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006480 assert(Result.isInvalid() &&
6481 "C++ binary operator overloading is missing candidates!");
6482 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006483 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006484 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006485 return move(Result);
6486 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006487
6488 case OR_Ambiguous:
6489 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6490 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006491 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006492 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006493 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006494 return ExprError();
6495
6496 case OR_Deleted:
6497 Diag(OpLoc, diag::err_ovl_deleted_oper)
6498 << Best->Function->isDeleted()
6499 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006500 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006501 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006502 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006503 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006504
Douglas Gregor66950a32009-09-30 21:46:01 +00006505 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006506 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006507}
6508
Sebastian Redladba46e2009-10-29 20:17:01 +00006509Action::OwningExprResult
6510Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6511 SourceLocation RLoc,
6512 ExprArg Base, ExprArg Idx) {
6513 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6514 static_cast<Expr*>(Idx.get()) };
6515 DeclarationName OpName =
6516 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6517
6518 // If either side is type-dependent, create an appropriate dependent
6519 // expression.
6520 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6521
John McCall58cc69d2010-01-27 01:50:18 +00006522 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006523 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006524 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006525 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006526 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006527 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006528
6529 Base.release();
6530 Idx.release();
6531 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6532 Args, 2,
6533 Context.DependentTy,
6534 RLoc));
6535 }
6536
6537 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006538 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006539
6540 // Subscript can only be overloaded as a member function.
6541
6542 // Add operator candidates that are member functions.
6543 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6544
6545 // Add builtin operator candidates.
6546 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6547
6548 // Perform overload resolution.
6549 OverloadCandidateSet::iterator Best;
6550 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6551 case OR_Success: {
6552 // We found a built-in operator or an overloaded operator.
6553 FunctionDecl *FnDecl = Best->Function;
6554
6555 if (FnDecl) {
6556 // We matched an overloaded operator. Build a call to that
6557 // operator.
6558
John McCalla0296f72010-03-19 07:35:19 +00006559 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006560 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006561
Sebastian Redladba46e2009-10-29 20:17:01 +00006562 // Convert the arguments.
6563 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006564 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006565 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006566 return ExprError();
6567
Anders Carlssona68e51e2010-01-29 18:37:50 +00006568 // Convert the arguments.
6569 OwningExprResult InputInit
6570 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6571 FnDecl->getParamDecl(0)),
6572 SourceLocation(),
6573 Owned(Args[1]));
6574 if (InputInit.isInvalid())
6575 return ExprError();
6576
6577 Args[1] = InputInit.takeAs<Expr>();
6578
Sebastian Redladba46e2009-10-29 20:17:01 +00006579 // Determine the result type
6580 QualType ResultTy
6581 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6582 ResultTy = ResultTy.getNonReferenceType();
6583
6584 // Build the actual expression node.
6585 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6586 LLoc);
6587 UsualUnaryConversions(FnExpr);
6588
6589 Base.release();
6590 Idx.release();
6591 ExprOwningPtr<CXXOperatorCallExpr>
6592 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6593 FnExpr, Args, 2,
6594 ResultTy, RLoc));
6595
6596 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6597 FnDecl))
6598 return ExprError();
6599
6600 return MaybeBindToTemporary(TheCall.release());
6601 } else {
6602 // We matched a built-in operator. Convert the arguments, then
6603 // break out so that we will build the appropriate built-in
6604 // operator node.
6605 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006606 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006607 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006608 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006609 return ExprError();
6610
6611 break;
6612 }
6613 }
6614
6615 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006616 if (CandidateSet.empty())
6617 Diag(LLoc, diag::err_ovl_no_oper)
6618 << Args[0]->getType() << /*subscript*/ 0
6619 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6620 else
6621 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6622 << Args[0]->getType()
6623 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006624 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006625 "[]", LLoc);
6626 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006627 }
6628
6629 case OR_Ambiguous:
6630 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6631 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006632 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006633 "[]", LLoc);
6634 return ExprError();
6635
6636 case OR_Deleted:
6637 Diag(LLoc, diag::err_ovl_deleted_oper)
6638 << Best->Function->isDeleted() << "[]"
6639 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006640 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006641 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006642 return ExprError();
6643 }
6644
6645 // We matched a built-in operator; build it.
6646 Base.release();
6647 Idx.release();
6648 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6649 Owned(Args[1]), RLoc);
6650}
6651
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006652/// BuildCallToMemberFunction - Build a call to a member
6653/// function. MemExpr is the expression that refers to the member
6654/// function (and includes the object parameter), Args/NumArgs are the
6655/// arguments to the function call (not including the object
6656/// parameter). The caller needs to validate that the member
6657/// expression refers to a member function or an overloaded member
6658/// function.
John McCall2d74de92009-12-01 22:10:20 +00006659Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006660Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6661 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006662 unsigned NumArgs, SourceLocation *CommaLocs,
6663 SourceLocation RParenLoc) {
6664 // Dig out the member expression. This holds both the object
6665 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006666 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6667
John McCall10eae182009-11-30 22:42:35 +00006668 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006669 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006670 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006671 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006672 if (isa<MemberExpr>(NakedMemExpr)) {
6673 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006674 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006675 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006676 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006677 } else {
6678 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006679 Qualifier = UnresExpr->getQualifier();
6680
John McCall6e9f8f62009-12-03 04:06:58 +00006681 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006682
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006683 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006684 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006685
John McCall2d74de92009-12-01 22:10:20 +00006686 // FIXME: avoid copy.
6687 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6688 if (UnresExpr->hasExplicitTemplateArgs()) {
6689 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6690 TemplateArgs = &TemplateArgsBuffer;
6691 }
6692
John McCall10eae182009-11-30 22:42:35 +00006693 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6694 E = UnresExpr->decls_end(); I != E; ++I) {
6695
John McCall6e9f8f62009-12-03 04:06:58 +00006696 NamedDecl *Func = *I;
6697 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6698 if (isa<UsingShadowDecl>(Func))
6699 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6700
John McCall10eae182009-11-30 22:42:35 +00006701 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006702 // If explicit template arguments were provided, we can't call a
6703 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006704 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006705 continue;
6706
John McCalla0296f72010-03-19 07:35:19 +00006707 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006708 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006709 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006710 } else {
John McCall10eae182009-11-30 22:42:35 +00006711 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006712 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006713 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006714 CandidateSet,
6715 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006716 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006717 }
Mike Stump11289f42009-09-09 15:08:12 +00006718
John McCall10eae182009-11-30 22:42:35 +00006719 DeclarationName DeclName = UnresExpr->getMemberName();
6720
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006721 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006722 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006723 case OR_Success:
6724 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006725 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006726 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006727 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006728 break;
6729
6730 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006731 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006732 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006733 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006734 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006735 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006736 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006737
6738 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006739 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006740 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006741 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006742 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006743 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006744
6745 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006746 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006747 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006748 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006749 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006750 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006751 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006752 }
6753
John McCall16df1e52010-03-30 21:47:33 +00006754 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006755
John McCall2d74de92009-12-01 22:10:20 +00006756 // If overload resolution picked a static member, build a
6757 // non-member call based on that function.
6758 if (Method->isStatic()) {
6759 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6760 Args, NumArgs, RParenLoc);
6761 }
6762
John McCall10eae182009-11-30 22:42:35 +00006763 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006764 }
6765
6766 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006767 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006768 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006769 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006770 Method->getResultType().getNonReferenceType(),
6771 RParenLoc));
6772
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006773 // Check for a valid return type.
6774 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6775 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006776 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006777
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006778 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006779 // We only need to do this if there was actually an overload; otherwise
6780 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006781 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006782 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006783 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6784 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006785 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006786 MemExpr->setBase(ObjectArg);
6787
6788 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00006789 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00006790 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006791 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006792 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006793
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006794 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006795 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006796
John McCall2d74de92009-12-01 22:10:20 +00006797 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006798}
6799
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006800/// BuildCallToObjectOfClassType - Build a call to an object of class
6801/// type (C++ [over.call.object]), which can end up invoking an
6802/// overloaded function call operator (@c operator()) or performing a
6803/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006804Sema::ExprResult
6805Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006806 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006807 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006808 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006809 SourceLocation RParenLoc) {
6810 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006811 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006812
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006813 // C++ [over.call.object]p1:
6814 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006815 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006816 // candidate functions includes at least the function call
6817 // operators of T. The function call operators of T are obtained by
6818 // ordinary lookup of the name operator() in the context of
6819 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006820 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006821 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006822
6823 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006824 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006825 << Object->getSourceRange()))
6826 return true;
6827
John McCall27b18f82009-11-17 02:14:36 +00006828 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6829 LookupQualifiedName(R, Record->getDecl());
6830 R.suppressDiagnostics();
6831
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006832 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006833 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006834 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006835 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006836 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006837 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006838
Douglas Gregorab7897a2008-11-19 22:57:39 +00006839 // C++ [over.call.object]p2:
6840 // In addition, for each conversion function declared in T of the
6841 // form
6842 //
6843 // operator conversion-type-id () cv-qualifier;
6844 //
6845 // where cv-qualifier is the same cv-qualification as, or a
6846 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006847 // denotes the type "pointer to function of (P1,...,Pn) returning
6848 // R", or the type "reference to pointer to function of
6849 // (P1,...,Pn) returning R", or the type "reference to function
6850 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006851 // is also considered as a candidate function. Similarly,
6852 // surrogate call functions are added to the set of candidate
6853 // functions for each conversion function declared in an
6854 // accessible base class provided the function is not hidden
6855 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006856 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006857 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006858 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006859 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006860 NamedDecl *D = *I;
6861 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6862 if (isa<UsingShadowDecl>(D))
6863 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6864
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006865 // Skip over templated conversion functions; they aren't
6866 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006867 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006868 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006869
John McCall6e9f8f62009-12-03 04:06:58 +00006870 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006871
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006872 // Strip the reference type (if any) and then the pointer type (if
6873 // any) to get down to what might be a function type.
6874 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6875 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6876 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006877
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006878 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006879 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006880 Object->getType(), Args, NumArgs,
6881 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006882 }
Mike Stump11289f42009-09-09 15:08:12 +00006883
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006884 // Perform overload resolution.
6885 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006886 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006887 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006888 // Overload resolution succeeded; we'll build the appropriate call
6889 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006890 break;
6891
6892 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006893 if (CandidateSet.empty())
6894 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6895 << Object->getType() << /*call*/ 1
6896 << Object->getSourceRange();
6897 else
6898 Diag(Object->getSourceRange().getBegin(),
6899 diag::err_ovl_no_viable_object_call)
6900 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006901 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006902 break;
6903
6904 case OR_Ambiguous:
6905 Diag(Object->getSourceRange().getBegin(),
6906 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006907 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006908 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006909 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006910
6911 case OR_Deleted:
6912 Diag(Object->getSourceRange().getBegin(),
6913 diag::err_ovl_deleted_object_call)
6914 << Best->Function->isDeleted()
6915 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006916 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006917 break;
Mike Stump11289f42009-09-09 15:08:12 +00006918 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006919
Douglas Gregorab7897a2008-11-19 22:57:39 +00006920 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006921 // We had an error; delete all of the subexpressions and return
6922 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006923 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006924 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006925 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006926 return true;
6927 }
6928
Douglas Gregorab7897a2008-11-19 22:57:39 +00006929 if (Best->Function == 0) {
6930 // Since there is no function declaration, this is one of the
6931 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006932 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006933 = cast<CXXConversionDecl>(
6934 Best->Conversions[0].UserDefined.ConversionFunction);
6935
John McCalla0296f72010-03-19 07:35:19 +00006936 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006937 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006938
Douglas Gregorab7897a2008-11-19 22:57:39 +00006939 // We selected one of the surrogate functions that converts the
6940 // object parameter to a function pointer. Perform the conversion
6941 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006942
6943 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006944 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006945 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6946 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006947
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006948 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006949 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006950 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006951 }
6952
John McCalla0296f72010-03-19 07:35:19 +00006953 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006954 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006955
Douglas Gregorab7897a2008-11-19 22:57:39 +00006956 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6957 // that calls this method, using Object for the implicit object
6958 // parameter and passing along the remaining arguments.
6959 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006960 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006961
6962 unsigned NumArgsInProto = Proto->getNumArgs();
6963 unsigned NumArgsToCheck = NumArgs;
6964
6965 // Build the full argument list for the method call (the
6966 // implicit object parameter is placed at the beginning of the
6967 // list).
6968 Expr **MethodArgs;
6969 if (NumArgs < NumArgsInProto) {
6970 NumArgsToCheck = NumArgsInProto;
6971 MethodArgs = new Expr*[NumArgsInProto + 1];
6972 } else {
6973 MethodArgs = new Expr*[NumArgs + 1];
6974 }
6975 MethodArgs[0] = Object;
6976 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6977 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006978
6979 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006980 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006981 UsualUnaryConversions(NewFn);
6982
6983 // Once we've built TheCall, all of the expressions are properly
6984 // owned.
6985 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006986 ExprOwningPtr<CXXOperatorCallExpr>
6987 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006988 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006989 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006990 delete [] MethodArgs;
6991
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006992 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6993 Method))
6994 return true;
6995
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006996 // We may have default arguments. If so, we need to allocate more
6997 // slots in the call for them.
6998 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006999 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007000 else if (NumArgs > NumArgsInProto)
7001 NumArgsToCheck = NumArgsInProto;
7002
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007003 bool IsError = false;
7004
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007005 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007006 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007007 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007008 TheCall->setArg(0, Object);
7009
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007010
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007011 // Check the argument types.
7012 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007013 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007014 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007015 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007016
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007017 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007018
7019 OwningExprResult InputInit
7020 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7021 Method->getParamDecl(i)),
7022 SourceLocation(), Owned(Arg));
7023
7024 IsError |= InputInit.isInvalid();
7025 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007026 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007027 OwningExprResult DefArg
7028 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7029 if (DefArg.isInvalid()) {
7030 IsError = true;
7031 break;
7032 }
7033
7034 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007035 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007036
7037 TheCall->setArg(i + 1, Arg);
7038 }
7039
7040 // If this is a variadic call, handle args passed through "...".
7041 if (Proto->isVariadic()) {
7042 // Promote the arguments (C99 6.5.2.2p7).
7043 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7044 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007045 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007046 TheCall->setArg(i + 1, Arg);
7047 }
7048 }
7049
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007050 if (IsError) return true;
7051
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007052 if (CheckFunctionCall(Method, TheCall.get()))
7053 return true;
7054
Douglas Gregore5e775b2010-04-13 15:50:39 +00007055 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007056}
7057
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007058/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007059/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007060/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007061Sema::OwningExprResult
7062Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7063 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007064 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007065
John McCallbc077cf2010-02-08 23:07:23 +00007066 SourceLocation Loc = Base->getExprLoc();
7067
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007068 // C++ [over.ref]p1:
7069 //
7070 // [...] An expression x->m is interpreted as (x.operator->())->m
7071 // for a class object x of type T if T::operator->() exists and if
7072 // the operator is selected as the best match function by the
7073 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007074 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007075 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007076 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007077
John McCallbc077cf2010-02-08 23:07:23 +00007078 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007079 PDiag(diag::err_typecheck_incomplete_tag)
7080 << Base->getSourceRange()))
7081 return ExprError();
7082
John McCall27b18f82009-11-17 02:14:36 +00007083 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7084 LookupQualifiedName(R, BaseRecord->getDecl());
7085 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007086
7087 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007088 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007089 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007090 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007091 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007092
7093 // Perform overload resolution.
7094 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007095 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007096 case OR_Success:
7097 // Overload resolution succeeded; we'll build the call below.
7098 break;
7099
7100 case OR_No_Viable_Function:
7101 if (CandidateSet.empty())
7102 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007103 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007104 else
7105 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007106 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007107 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007108 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007109
7110 case OR_Ambiguous:
7111 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007112 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007113 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007114 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007115
7116 case OR_Deleted:
7117 Diag(OpLoc, diag::err_ovl_deleted_oper)
7118 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007119 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007120 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007121 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007122 }
7123
John McCalla0296f72010-03-19 07:35:19 +00007124 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007125 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007126
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007127 // Convert the object parameter.
7128 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007129 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7130 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007131 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007132
7133 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007134 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007135
7136 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007137 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7138 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007139 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007140
7141 QualType ResultTy = Method->getResultType().getNonReferenceType();
7142 ExprOwningPtr<CXXOperatorCallExpr>
7143 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7144 &Base, 1, ResultTy, OpLoc));
7145
7146 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7147 Method))
7148 return ExprError();
7149 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007150}
7151
Douglas Gregorcd695e52008-11-10 20:40:00 +00007152/// FixOverloadedFunctionReference - E is an expression that refers to
7153/// a C++ overloaded function (possibly with some parentheses and
7154/// perhaps a '&' around it). We have resolved the overloaded function
7155/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007156/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007157Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007158 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007159 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007160 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7161 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007162 if (SubExpr == PE->getSubExpr())
7163 return PE->Retain();
7164
7165 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7166 }
7167
7168 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007169 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7170 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007171 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007172 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007173 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007174 if (SubExpr == ICE->getSubExpr())
7175 return ICE->Retain();
7176
7177 return new (Context) ImplicitCastExpr(ICE->getType(),
7178 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007179 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007180 ICE->isLvalueCast());
7181 }
7182
7183 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007184 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007185 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007186 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7187 if (Method->isStatic()) {
7188 // Do nothing: static member functions aren't any different
7189 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007190 } else {
John McCalle66edc12009-11-24 19:00:30 +00007191 // Fix the sub expression, which really has to be an
7192 // UnresolvedLookupExpr holding an overloaded member function
7193 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007194 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7195 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007196 if (SubExpr == UnOp->getSubExpr())
7197 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007198
John McCalld14a8642009-11-21 08:51:07 +00007199 assert(isa<DeclRefExpr>(SubExpr)
7200 && "fixed to something other than a decl ref");
7201 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7202 && "fixed to a member ref with no nested name qualifier");
7203
7204 // We have taken the address of a pointer to member
7205 // function. Perform the computation here so that we get the
7206 // appropriate pointer to member type.
7207 QualType ClassType
7208 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7209 QualType MemPtrType
7210 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7211
7212 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7213 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007214 }
7215 }
John McCall16df1e52010-03-30 21:47:33 +00007216 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7217 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007218 if (SubExpr == UnOp->getSubExpr())
7219 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007220
Douglas Gregor51c538b2009-11-20 19:42:02 +00007221 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7222 Context.getPointerType(SubExpr->getType()),
7223 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007224 }
John McCalld14a8642009-11-21 08:51:07 +00007225
7226 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007227 // FIXME: avoid copy.
7228 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007229 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007230 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7231 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007232 }
7233
John McCalld14a8642009-11-21 08:51:07 +00007234 return DeclRefExpr::Create(Context,
7235 ULE->getQualifier(),
7236 ULE->getQualifierRange(),
7237 Fn,
7238 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007239 Fn->getType(),
7240 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007241 }
7242
John McCall10eae182009-11-30 22:42:35 +00007243 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007244 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007245 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7246 if (MemExpr->hasExplicitTemplateArgs()) {
7247 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7248 TemplateArgs = &TemplateArgsBuffer;
7249 }
John McCall6b51f282009-11-23 01:53:49 +00007250
John McCall2d74de92009-12-01 22:10:20 +00007251 Expr *Base;
7252
7253 // If we're filling in
7254 if (MemExpr->isImplicitAccess()) {
7255 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7256 return DeclRefExpr::Create(Context,
7257 MemExpr->getQualifier(),
7258 MemExpr->getQualifierRange(),
7259 Fn,
7260 MemExpr->getMemberLoc(),
7261 Fn->getType(),
7262 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007263 } else {
7264 SourceLocation Loc = MemExpr->getMemberLoc();
7265 if (MemExpr->getQualifier())
7266 Loc = MemExpr->getQualifierRange().getBegin();
7267 Base = new (Context) CXXThisExpr(Loc,
7268 MemExpr->getBaseType(),
7269 /*isImplicit=*/true);
7270 }
John McCall2d74de92009-12-01 22:10:20 +00007271 } else
7272 Base = MemExpr->getBase()->Retain();
7273
7274 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007275 MemExpr->isArrow(),
7276 MemExpr->getQualifier(),
7277 MemExpr->getQualifierRange(),
7278 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007279 Found,
John McCall6b51f282009-11-23 01:53:49 +00007280 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007281 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007282 Fn->getType());
7283 }
7284
Douglas Gregor51c538b2009-11-20 19:42:02 +00007285 assert(false && "Invalid reference to overloaded function");
7286 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007287}
7288
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007289Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007290 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007291 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007292 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007293}
7294
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007295} // end namespace clang