blob: 602a118c3b7f4fafc9689bcbc8b18885def7fa33 [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
39static Expr *
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43 S.DefaultFunctionArrayConversion(E);
44 return E;
45}
46
John McCall5c32be02010-08-24 20:38:10 +000047static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48 bool InOverloadResolution,
49 StandardConversionSequence &SCS);
50static OverloadingResult
51IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
52 UserDefinedConversionSequence& User,
53 OverloadCandidateSet& Conversions,
54 bool AllowExplicit);
55
56
57static ImplicitConversionSequence::CompareKind
58CompareStandardConversionSequences(Sema &S,
59 const StandardConversionSequence& SCS1,
60 const StandardConversionSequence& SCS2);
61
62static ImplicitConversionSequence::CompareKind
63CompareQualificationConversions(Sema &S,
64 const StandardConversionSequence& SCS1,
65 const StandardConversionSequence& SCS2);
66
67static ImplicitConversionSequence::CompareKind
68CompareDerivedToBaseConversions(Sema &S,
69 const StandardConversionSequence& SCS1,
70 const StandardConversionSequence& SCS2);
71
72
73
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074/// GetConversionCategory - Retrieve the implicit conversion
75/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000076ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000077GetConversionCategory(ImplicitConversionKind Kind) {
78 static const ImplicitConversionCategory
79 Category[(int)ICK_Num_Conversion_Kinds] = {
80 ICC_Identity,
81 ICC_Lvalue_Transformation,
82 ICC_Lvalue_Transformation,
83 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000084 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 ICC_Qualification_Adjustment,
86 ICC_Promotion,
87 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000088 ICC_Promotion,
89 ICC_Conversion,
90 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000091 ICC_Conversion,
92 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
95 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000096 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000097 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000098 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Conversion
101 };
102 return Category[(int)Kind];
103}
104
105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
107ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000130 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000131 };
132 return Rank[(int)Kind];
133}
134
135/// GetImplicitConversionName - Return the name of this kind of
136/// implicit conversion.
137const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000138 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 "No conversion",
140 "Lvalue-to-rvalue",
141 "Array-to-pointer",
142 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000143 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 "Qualification",
145 "Integral promotion",
146 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000147 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000148 "Integral conversion",
149 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000150 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "Floating-integral conversion",
152 "Pointer conversion",
153 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000154 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000155 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000156 "Derived-to-base conversion",
157 "Vector conversion",
158 "Vector splat",
159 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 };
161 return Name[Kind];
162}
163
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000164/// StandardConversionSequence - Set the standard conversion
165/// sequence to the identity conversion.
166void StandardConversionSequence::setAsIdentityConversion() {
167 First = ICK_Identity;
168 Second = ICK_Identity;
169 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000170 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000171 ReferenceBinding = false;
172 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000173 IsLvalueReference = true;
174 BindsToFunctionLvalue = false;
175 BindsToRvalue = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000176 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000177}
178
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179/// getRank - Retrieve the rank of this standard conversion sequence
180/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
181/// implicit conversions.
182ImplicitConversionRank StandardConversionSequence::getRank() const {
183 ImplicitConversionRank Rank = ICR_Exact_Match;
184 if (GetConversionRank(First) > Rank)
185 Rank = GetConversionRank(First);
186 if (GetConversionRank(Second) > Rank)
187 Rank = GetConversionRank(Second);
188 if (GetConversionRank(Third) > Rank)
189 Rank = GetConversionRank(Third);
190 return Rank;
191}
192
193/// isPointerConversionToBool - Determines whether this conversion is
194/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000195/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000196/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000197bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000198 // Note that FromType has not necessarily been transformed by the
199 // array-to-pointer or function-to-pointer implicit conversions, so
200 // check for their presence as well as checking whether FromType is
201 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000202 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000203 (getFromType()->isPointerType() ||
204 getFromType()->isObjCObjectPointerType() ||
205 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000206 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000207 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
208 return true;
209
210 return false;
211}
212
Douglas Gregor5c407d92008-10-23 00:40:37 +0000213/// isPointerConversionToVoidPointer - Determines whether this
214/// conversion is a conversion of a pointer to a void pointer. This is
215/// used as part of the ranking of standard conversion sequences (C++
216/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000217bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000218StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000219isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000220 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000221 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000222
223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer implicit conversion, so check for its presence
225 // and redo the conversion to get a pointer.
226 if (First == ICK_Array_To_Pointer)
227 FromType = Context.getArrayDecayedType(FromType);
228
John McCall75851b12010-10-26 06:40:27 +0000229 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000230 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000231 return ToPtrType->getPointeeType()->isVoidType();
232
233 return false;
234}
235
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000236/// DebugPrint - Print this standard conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 bool PrintedSomething = false;
241 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 PrintedSomething = true;
244 }
245
246 if (Second != ICK_Identity) {
247 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000248 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000249 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000251
252 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000254 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000255 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000256 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000257 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000258 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000259 PrintedSomething = true;
260 }
261
262 if (Third != ICK_Identity) {
263 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000266 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000267 PrintedSomething = true;
268 }
269
270 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000271 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000272 }
273}
274
275/// DebugPrint - Print this user-defined conversion sequence to standard
276/// error. Useful for debugging overloading issues.
277void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279 if (Before.First || Before.Second || Before.Third) {
280 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000281 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000282 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000283 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000285 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000286 After.DebugPrint();
287 }
288}
289
290/// DebugPrint - Print this implicit conversion sequence to standard
291/// error. Useful for debugging overloading issues.
292void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000293 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 switch (ConversionKind) {
295 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000296 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000297 Standard.DebugPrint();
298 break;
299 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000300 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301 UserDefined.DebugPrint();
302 break;
303 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000304 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000305 break;
John McCall0d1da222010-01-12 00:44:57 +0000306 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000307 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000308 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000309 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000310 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000311 break;
312 }
313
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000314 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000315}
316
John McCall0d1da222010-01-12 00:44:57 +0000317void AmbiguousConversionSequence::construct() {
318 new (&conversions()) ConversionSet();
319}
320
321void AmbiguousConversionSequence::destruct() {
322 conversions().~ConversionSet();
323}
324
325void
326AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
327 FromTypePtr = O.FromTypePtr;
328 ToTypePtr = O.ToTypePtr;
329 new (&conversions()) ConversionSet(O.conversions());
330}
331
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000332namespace {
333 // Structure used by OverloadCandidate::DeductionFailureInfo to store
334 // template parameter and template argument information.
335 struct DFIParamWithArguments {
336 TemplateParameter Param;
337 TemplateArgument FirstArg;
338 TemplateArgument SecondArg;
339 };
340}
341
342/// \brief Convert from Sema's representation of template deduction information
343/// to the form used in overload-candidate information.
344OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000345static MakeDeductionFailureInfo(ASTContext &Context,
346 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000347 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000348 OverloadCandidate::DeductionFailureInfo Result;
349 Result.Result = static_cast<unsigned>(TDK);
350 Result.Data = 0;
351 switch (TDK) {
352 case Sema::TDK_Success:
353 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000354 case Sema::TDK_TooManyArguments:
355 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000356 break;
357
358 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000359 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360 Result.Data = Info.Param.getOpaqueValue();
361 break;
362
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000363 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000364 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000365 // FIXME: Should allocate from normal heap so that we can free this later.
366 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000367 Saved->Param = Info.Param;
368 Saved->FirstArg = Info.FirstArg;
369 Saved->SecondArg = Info.SecondArg;
370 Result.Data = Saved;
371 break;
372 }
373
374 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000375 Result.Data = Info.take();
376 break;
377
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000378 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000379 case Sema::TDK_FailedOverloadResolution:
380 break;
381 }
382
383 return Result;
384}
John McCall0d1da222010-01-12 00:44:57 +0000385
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386void OverloadCandidate::DeductionFailureInfo::Destroy() {
387 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
388 case Sema::TDK_Success:
389 case Sema::TDK_InstantiationDepth:
390 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000391 case Sema::TDK_TooManyArguments:
392 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000393 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000394 break;
395
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000397 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000398 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000399 Data = 0;
400 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000401
402 case Sema::TDK_SubstitutionFailure:
403 // FIXME: Destroy the template arugment list?
404 Data = 0;
405 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406
Douglas Gregor461761d2010-05-08 18:20:53 +0000407 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000409 case Sema::TDK_FailedOverloadResolution:
410 break;
411 }
412}
413
414TemplateParameter
415OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
416 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
417 case Sema::TDK_Success:
418 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000419 case Sema::TDK_TooManyArguments:
420 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000421 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000422 return TemplateParameter();
423
424 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000425 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000426 return TemplateParameter::getFromOpaqueValue(Data);
427
428 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000429 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000430 return static_cast<DFIParamWithArguments*>(Data)->Param;
431
432 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000433 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000434 case Sema::TDK_FailedOverloadResolution:
435 break;
436 }
437
438 return TemplateParameter();
439}
Douglas Gregord09efd42010-05-08 20:07:26 +0000440
441TemplateArgumentList *
442OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
443 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
444 case Sema::TDK_Success:
445 case Sema::TDK_InstantiationDepth:
446 case Sema::TDK_TooManyArguments:
447 case Sema::TDK_TooFewArguments:
448 case Sema::TDK_Incomplete:
449 case Sema::TDK_InvalidExplicitArguments:
450 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000451 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000452 return 0;
453
454 case Sema::TDK_SubstitutionFailure:
455 return static_cast<TemplateArgumentList*>(Data);
456
457 // Unhandled
458 case Sema::TDK_NonDeducedMismatch:
459 case Sema::TDK_FailedOverloadResolution:
460 break;
461 }
462
463 return 0;
464}
465
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000466const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
467 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
468 case Sema::TDK_Success:
469 case Sema::TDK_InstantiationDepth:
470 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000471 case Sema::TDK_TooManyArguments:
472 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000473 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000474 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000475 return 0;
476
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000477 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000478 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000479 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
480
Douglas Gregor461761d2010-05-08 18:20:53 +0000481 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000482 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000483 case Sema::TDK_FailedOverloadResolution:
484 break;
485 }
486
487 return 0;
488}
489
490const TemplateArgument *
491OverloadCandidate::DeductionFailureInfo::getSecondArg() {
492 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
493 case Sema::TDK_Success:
494 case Sema::TDK_InstantiationDepth:
495 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000496 case Sema::TDK_TooManyArguments:
497 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000498 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000499 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000500 return 0;
501
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000503 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000504 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
505
Douglas Gregor461761d2010-05-08 18:20:53 +0000506 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000507 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000508 case Sema::TDK_FailedOverloadResolution:
509 break;
510 }
511
512 return 0;
513}
514
515void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000516 inherited::clear();
517 Functions.clear();
518}
519
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000521// overload of the declarations in Old. This routine returns false if
522// New and Old cannot be overloaded, e.g., if New has the same
523// signature as some function in Old (C++ 1.3.10) or if the Old
524// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000525// it does return false, MatchedDecl will point to the decl that New
526// cannot be overloaded with. This decl may be a UsingShadowDecl on
527// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528//
529// Example: Given the following input:
530//
531// void f(int, float); // #1
532// void f(int, int); // #2
533// int f(int, int); // #3
534//
535// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000536// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537//
John McCall3d988d92009-12-02 08:47:38 +0000538// When we process #2, Old contains only the FunctionDecl for #1. By
539// comparing the parameter types, we see that #1 and #2 are overloaded
540// (since they have different signatures), so this routine returns
541// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542//
John McCall3d988d92009-12-02 08:47:38 +0000543// When we process #3, Old is an overload set containing #1 and #2. We
544// compare the signatures of #3 to #1 (they're overloaded, so we do
545// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
546// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000547// signature), IsOverload returns false and MatchedDecl will be set to
548// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000549//
550// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
551// into a class by a using declaration. The rules for whether to hide
552// shadow declarations ignore some properties which otherwise figure
553// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000554Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000555Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
556 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000557 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000558 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000559 NamedDecl *OldD = *I;
560
561 bool OldIsUsingDecl = false;
562 if (isa<UsingShadowDecl>(OldD)) {
563 OldIsUsingDecl = true;
564
565 // We can always introduce two using declarations into the same
566 // context, even if they have identical signatures.
567 if (NewIsUsingDecl) continue;
568
569 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
570 }
571
572 // If either declaration was introduced by a using declaration,
573 // we'll need to use slightly different rules for matching.
574 // Essentially, these rules are the normal rules, except that
575 // function templates hide function templates with different
576 // return types or template parameter lists.
577 bool UseMemberUsingDeclRules =
578 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
579
John McCall3d988d92009-12-02 08:47:38 +0000580 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000581 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
582 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
583 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
584 continue;
585 }
586
John McCalldaa3d6b2009-12-09 03:35:25 +0000587 Match = *I;
588 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000589 }
John McCall3d988d92009-12-02 08:47:38 +0000590 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000591 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
592 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
593 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
594 continue;
595 }
596
John McCalldaa3d6b2009-12-09 03:35:25 +0000597 Match = *I;
598 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000599 }
John McCalla8987a2942010-11-10 03:01:53 +0000600 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000601 // We can overload with these, which can show up when doing
602 // redeclaration checks for UsingDecls.
603 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000604 } else if (isa<TagDecl>(OldD)) {
605 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000606 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
607 // Optimistically assume that an unresolved using decl will
608 // overload; if it doesn't, we'll have to diagnose during
609 // template instantiation.
610 } else {
John McCall1f82f242009-11-18 22:49:29 +0000611 // (C++ 13p1):
612 // Only function declarations can be overloaded; object and type
613 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000614 Match = *I;
615 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000616 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000617 }
John McCall1f82f242009-11-18 22:49:29 +0000618
John McCalldaa3d6b2009-12-09 03:35:25 +0000619 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000620}
621
John McCalle9cccd82010-06-16 08:42:20 +0000622bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
623 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000624 // If both of the functions are extern "C", then they are not
625 // overloads.
626 if (Old->isExternC() && New->isExternC())
627 return false;
628
John McCall1f82f242009-11-18 22:49:29 +0000629 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
630 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
631
632 // C++ [temp.fct]p2:
633 // A function template can be overloaded with other function templates
634 // and with normal (non-template) functions.
635 if ((OldTemplate == 0) != (NewTemplate == 0))
636 return true;
637
638 // Is the function New an overload of the function Old?
639 QualType OldQType = Context.getCanonicalType(Old->getType());
640 QualType NewQType = Context.getCanonicalType(New->getType());
641
642 // Compare the signatures (C++ 1.3.10) of the two functions to
643 // determine whether they are overloads. If we find any mismatch
644 // in the signature, they are overloads.
645
646 // If either of these functions is a K&R-style function (no
647 // prototype), then we consider them to have matching signatures.
648 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
649 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
650 return false;
651
John McCall424cec92011-01-19 06:33:43 +0000652 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
653 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000654
655 // The signature of a function includes the types of its
656 // parameters (C++ 1.3.10), which includes the presence or absence
657 // of the ellipsis; see C++ DR 357).
658 if (OldQType != NewQType &&
659 (OldType->getNumArgs() != NewType->getNumArgs() ||
660 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000661 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000662 return true;
663
664 // C++ [temp.over.link]p4:
665 // The signature of a function template consists of its function
666 // signature, its return type and its template parameter list. The names
667 // of the template parameters are significant only for establishing the
668 // relationship between the template parameters and the rest of the
669 // signature.
670 //
671 // We check the return type and template parameter lists for function
672 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000673 //
674 // However, we don't consider either of these when deciding whether
675 // a member introduced by a shadow declaration is hidden.
676 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000677 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
678 OldTemplate->getTemplateParameters(),
679 false, TPL_TemplateMatch) ||
680 OldType->getResultType() != NewType->getResultType()))
681 return true;
682
683 // If the function is a class member, its signature includes the
684 // cv-qualifiers (if any) on the function itself.
685 //
686 // As part of this, also check whether one of the member functions
687 // is static, in which case they are not overloads (C++
688 // 13.1p2). While not part of the definition of the signature,
689 // this check is important to determine whether these functions
690 // can be overloaded.
691 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
692 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
693 if (OldMethod && NewMethod &&
694 !OldMethod->isStatic() && !NewMethod->isStatic() &&
695 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
696 return true;
697
698 // The signatures match; this is not an overload.
699 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000700}
701
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000702/// TryImplicitConversion - Attempt to perform an implicit conversion
703/// from the given expression (Expr) to the given type (ToType). This
704/// function returns an implicit conversion sequence that can be used
705/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000706///
707/// void f(float f);
708/// void g(int i) { f(i); }
709///
710/// this routine would produce an implicit conversion sequence to
711/// describe the initialization of f from i, which will be a standard
712/// conversion sequence containing an lvalue-to-rvalue conversion (C++
713/// 4.1) followed by a floating-integral conversion (C++ 4.9).
714//
715/// Note that this routine only determines how the conversion can be
716/// performed; it does not actually perform the conversion. As such,
717/// it will not produce any diagnostics if no conversion is available,
718/// but will instead return an implicit conversion sequence of kind
719/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000720///
721/// If @p SuppressUserConversions, then user-defined conversions are
722/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000723/// If @p AllowExplicit, then explicit user-defined conversions are
724/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000725static ImplicitConversionSequence
726TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
727 bool SuppressUserConversions,
728 bool AllowExplicit,
729 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000730 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000731 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
732 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000733 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000734 return ICS;
735 }
736
John McCall5c32be02010-08-24 20:38:10 +0000737 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000738 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000739 return ICS;
740 }
741
Douglas Gregor836a7e82010-08-11 02:15:33 +0000742 // C++ [over.ics.user]p4:
743 // A conversion of an expression of class type to the same class
744 // type is given Exact Match rank, and a conversion of an
745 // expression of class type to a base class of that type is
746 // given Conversion rank, in spite of the fact that a copy/move
747 // constructor (i.e., a user-defined conversion function) is
748 // called for those cases.
749 QualType FromType = From->getType();
750 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000751 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
752 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000753 ICS.setStandard();
754 ICS.Standard.setAsIdentityConversion();
755 ICS.Standard.setFromType(FromType);
756 ICS.Standard.setAllToTypes(ToType);
757
758 // We don't actually check at this point whether there is a valid
759 // copy/move constructor, since overloading just assumes that it
760 // exists. When we actually perform initialization, we'll find the
761 // appropriate constructor to copy the returned object, if needed.
762 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000763
Douglas Gregor5ab11652010-04-17 22:01:05 +0000764 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000765 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000766 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000767
768 return ICS;
769 }
770
771 if (SuppressUserConversions) {
772 // We're not in the case above, so there is no conversion that
773 // we can perform.
774 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000775 return ICS;
776 }
777
778 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000779 OverloadCandidateSet Conversions(From->getExprLoc());
780 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000781 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000782 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000783
784 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000785 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000786 // C++ [over.ics.user]p4:
787 // A conversion of an expression of class type to the same class
788 // type is given Exact Match rank, and a conversion of an
789 // expression of class type to a base class of that type is
790 // given Conversion rank, in spite of the fact that a copy
791 // constructor (i.e., a user-defined conversion function) is
792 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000793 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000794 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000795 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000796 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
797 QualType ToCanon
798 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000799 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000800 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000801 // Turn this into a "standard" conversion sequence, so that it
802 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000803 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000804 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000805 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000806 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000807 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000808 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000809 ICS.Standard.Second = ICK_Derived_To_Base;
810 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000811 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000812
813 // C++ [over.best.ics]p4:
814 // However, when considering the argument of a user-defined
815 // conversion function that is a candidate by 13.3.1.3 when
816 // invoked for the copying of the temporary in the second step
817 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
818 // 13.3.1.6 in all cases, only standard conversion sequences and
819 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000820 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000821 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000822 }
John McCalle8c8cd22010-01-13 22:30:33 +0000823 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000824 ICS.setAmbiguous();
825 ICS.Ambiguous.setFromType(From->getType());
826 ICS.Ambiguous.setToType(ToType);
827 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
828 Cand != Conversions.end(); ++Cand)
829 if (Cand->Viable)
830 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000831 } else {
John McCall65eb8792010-02-25 01:37:24 +0000832 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000833 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000834
835 return ICS;
836}
837
John McCall5c32be02010-08-24 20:38:10 +0000838bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
839 const InitializedEntity &Entity,
840 Expr *Initializer,
841 bool SuppressUserConversions,
842 bool AllowExplicitConversions,
843 bool InOverloadResolution) {
844 ImplicitConversionSequence ICS
845 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
846 SuppressUserConversions,
847 AllowExplicitConversions,
848 InOverloadResolution);
849 if (ICS.isBad()) return true;
850
851 // Perform the actual conversion.
852 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
853 return false;
854}
855
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000856/// PerformImplicitConversion - Perform an implicit conversion of the
857/// expression From to the type ToType. Returns true if there was an
858/// error, false otherwise. The expression From is replaced with the
859/// converted expression. Flavor is the kind of conversion we're
860/// performing, used in the error message. If @p AllowExplicit,
861/// explicit user-defined conversions are permitted.
862bool
863Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
864 AssignmentAction Action, bool AllowExplicit) {
865 ImplicitConversionSequence ICS;
866 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
867}
868
869bool
870Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
871 AssignmentAction Action, bool AllowExplicit,
872 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000873 ICS = clang::TryImplicitConversion(*this, From, ToType,
874 /*SuppressUserConversions=*/false,
875 AllowExplicit,
876 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000877 return PerformImplicitConversion(From, ToType, ICS, Action);
878}
879
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000880/// \brief Determine whether the conversion from FromType to ToType is a valid
881/// conversion that strips "noreturn" off the nested function type.
882static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
883 QualType ToType, QualType &ResultTy) {
884 if (Context.hasSameUnqualifiedType(FromType, ToType))
885 return false;
886
John McCall991eb4b2010-12-21 00:44:39 +0000887 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
888 // where F adds one of the following at most once:
889 // - a pointer
890 // - a member pointer
891 // - a block pointer
892 CanQualType CanTo = Context.getCanonicalType(ToType);
893 CanQualType CanFrom = Context.getCanonicalType(FromType);
894 Type::TypeClass TyClass = CanTo->getTypeClass();
895 if (TyClass != CanFrom->getTypeClass()) return false;
896 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
897 if (TyClass == Type::Pointer) {
898 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
899 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
900 } else if (TyClass == Type::BlockPointer) {
901 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
902 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
903 } else if (TyClass == Type::MemberPointer) {
904 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
905 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
906 } else {
907 return false;
908 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000909
John McCall991eb4b2010-12-21 00:44:39 +0000910 TyClass = CanTo->getTypeClass();
911 if (TyClass != CanFrom->getTypeClass()) return false;
912 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
913 return false;
914 }
915
916 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
917 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
918 if (!EInfo.getNoReturn()) return false;
919
920 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
921 assert(QualType(FromFn, 0).isCanonical());
922 if (QualType(FromFn, 0) != CanTo) return false;
923
924 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000925 return true;
926}
Douglas Gregor46188682010-05-18 22:42:18 +0000927
928/// \brief Determine whether the conversion from FromType to ToType is a valid
929/// vector conversion.
930///
931/// \param ICK Will be set to the vector conversion kind, if this is a vector
932/// conversion.
933static bool IsVectorConversion(ASTContext &Context, QualType FromType,
934 QualType ToType, ImplicitConversionKind &ICK) {
935 // We need at least one of these types to be a vector type to have a vector
936 // conversion.
937 if (!ToType->isVectorType() && !FromType->isVectorType())
938 return false;
939
940 // Identical types require no conversions.
941 if (Context.hasSameUnqualifiedType(FromType, ToType))
942 return false;
943
944 // There are no conversions between extended vector types, only identity.
945 if (ToType->isExtVectorType()) {
946 // There are no conversions between extended vector types other than the
947 // identity conversion.
948 if (FromType->isExtVectorType())
949 return false;
950
951 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000952 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000953 ICK = ICK_Vector_Splat;
954 return true;
955 }
956 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000957
958 // We can perform the conversion between vector types in the following cases:
959 // 1)vector types are equivalent AltiVec and GCC vector types
960 // 2)lax vector conversions are permitted and the vector types are of the
961 // same size
962 if (ToType->isVectorType() && FromType->isVectorType()) {
963 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000964 (Context.getLangOptions().LaxVectorConversions &&
965 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000966 ICK = ICK_Vector_Conversion;
967 return true;
968 }
Douglas Gregor46188682010-05-18 22:42:18 +0000969 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000970
Douglas Gregor46188682010-05-18 22:42:18 +0000971 return false;
972}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000973
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000974/// IsStandardConversion - Determines whether there is a standard
975/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
976/// expression From to the type ToType. Standard conversion sequences
977/// only consider non-class types; for conversions that involve class
978/// types, use TryImplicitConversion. If a conversion exists, SCS will
979/// contain the standard conversion sequence required to perform this
980/// conversion and this routine will return true. Otherwise, this
981/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000982static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
983 bool InOverloadResolution,
984 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000985 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000986
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000987 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000988 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000989 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000990 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000991 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000992 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000993
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000994 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000995 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000996 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000997 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000998 return false;
999
Mike Stump11289f42009-09-09 15:08:12 +00001000 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001001 }
1002
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001003 // The first conversion can be an lvalue-to-rvalue conversion,
1004 // array-to-pointer conversion, or function-to-pointer conversion
1005 // (C++ 4p1).
1006
John McCall5c32be02010-08-24 20:38:10 +00001007 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001008 DeclAccessPair AccessPair;
1009 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +00001010 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1011 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001012 // We were able to resolve the address of the overloaded function,
1013 // so we can convert to the type of that function.
1014 FromType = Fn->getType();
1015 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1016 if (!Method->isStatic()) {
John McCall424cec92011-01-19 06:33:43 +00001017 const Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +00001018 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1019 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001020 }
1021 }
1022
1023 // If the "from" expression takes the address of the overloaded
1024 // function, update the type of the resulting expression accordingly.
1025 if (FromType->getAs<FunctionType>())
1026 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001027 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +00001028 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001029
1030 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00001031 assert(S.Context.hasSameType(FromType,
1032 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001033 } else {
1034 return false;
1035 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001036 }
Mike Stump11289f42009-09-09 15:08:12 +00001037 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001038 // An lvalue (3.10) of a non-function, non-array type T can be
1039 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001040 bool argIsLValue = From->isLValue();
1041 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001042 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001043 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001044 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001045
1046 // If T is a non-class type, the type of the rvalue is the
1047 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001048 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1049 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001050 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001051 } else if (FromType->isArrayType()) {
1052 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001053 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001054
1055 // An lvalue or rvalue of type "array of N T" or "array of unknown
1056 // bound of T" can be converted to an rvalue of type "pointer to
1057 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001058 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059
John McCall5c32be02010-08-24 20:38:10 +00001060 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001062 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001063
1064 // For the purpose of ranking in overload resolution
1065 // (13.3.3.1.1), this conversion is considered an
1066 // array-to-pointer conversion followed by a qualification
1067 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001068 SCS.Second = ICK_Identity;
1069 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001070 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001071 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001072 }
John McCall086a4642010-11-24 05:12:34 +00001073 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001074 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001075 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001076
1077 // An lvalue of function type T can be converted to an rvalue of
1078 // type "pointer to T." The result is a pointer to the
1079 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001080 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001081 } else {
1082 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001083 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001084 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001085 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001086
1087 // The second conversion can be an integral promotion, floating
1088 // point promotion, integral conversion, floating point conversion,
1089 // floating-integral conversion, pointer conversion,
1090 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001091 // For overloading in C, this can also be a "compatible-type"
1092 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001093 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001094 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001095 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001096 // The unqualified versions of the types are the same: there's no
1097 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001098 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001099 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001100 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001101 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001102 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001103 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001104 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001105 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001106 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001107 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001108 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001109 SCS.Second = ICK_Complex_Promotion;
1110 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001111 } else if (ToType->isBooleanType() &&
1112 (FromType->isArithmeticType() ||
1113 FromType->isAnyPointerType() ||
1114 FromType->isBlockPointerType() ||
1115 FromType->isMemberPointerType() ||
1116 FromType->isNullPtrType())) {
1117 // Boolean conversions (C++ 4.12).
1118 SCS.Second = ICK_Boolean_Conversion;
1119 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001120 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001121 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001122 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001123 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001125 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001126 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001127 SCS.Second = ICK_Complex_Conversion;
1128 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001129 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1130 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001131 // Complex-real conversions (C99 6.3.1.7)
1132 SCS.Second = ICK_Complex_Real;
1133 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001134 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001135 // Floating point conversions (C++ 4.8).
1136 SCS.Second = ICK_Floating_Conversion;
1137 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001138 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001139 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001140 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001141 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001142 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001143 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001144 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001145 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1146 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001147 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001148 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001149 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001150 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1151 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001152 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001153 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001154 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001155 SCS.Second = SecondICK;
1156 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001157 } else if (!S.getLangOptions().CPlusPlus &&
1158 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001159 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001160 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001161 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001162 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001163 // Treat a conversion that strips "noreturn" as an identity conversion.
1164 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001165 } else {
1166 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001167 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001169 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001171 QualType CanonFrom;
1172 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001173 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001174 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001175 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001176 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001177 CanonFrom = S.Context.getCanonicalType(FromType);
1178 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001179 } else {
1180 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001181 SCS.Third = ICK_Identity;
1182
Mike Stump11289f42009-09-09 15:08:12 +00001183 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001184 // [...] Any difference in top-level cv-qualification is
1185 // subsumed by the initialization itself and does not constitute
1186 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001187 CanonFrom = S.Context.getCanonicalType(FromType);
1188 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001189 if (CanonFrom.getLocalUnqualifiedType()
1190 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001191 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1192 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001193 FromType = ToType;
1194 CanonFrom = CanonTo;
1195 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001196 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001197 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001198
1199 // If we have not converted the argument type to the parameter type,
1200 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001201 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001202 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001203
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001204 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001205}
1206
1207/// IsIntegralPromotion - Determines whether the conversion from the
1208/// expression From (whose potentially-adjusted type is FromType) to
1209/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1210/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001211bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001212 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001213 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001214 if (!To) {
1215 return false;
1216 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001217
1218 // An rvalue of type char, signed char, unsigned char, short int, or
1219 // unsigned short int can be converted to an rvalue of type int if
1220 // int can represent all the values of the source type; otherwise,
1221 // the source rvalue can be converted to an rvalue of type unsigned
1222 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001223 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1224 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001225 if (// We can promote any signed, promotable integer type to an int
1226 (FromType->isSignedIntegerType() ||
1227 // We can promote any unsigned integer type whose size is
1228 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001229 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001230 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001231 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001232 }
1233
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001234 return To->getKind() == BuiltinType::UInt;
1235 }
1236
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001237 // C++0x [conv.prom]p3:
1238 // A prvalue of an unscoped enumeration type whose underlying type is not
1239 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1240 // following types that can represent all the values of the enumeration
1241 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1242 // unsigned int, long int, unsigned long int, long long int, or unsigned
1243 // long long int. If none of the types in that list can represent all the
1244 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1245 // type can be converted to an rvalue a prvalue of the extended integer type
1246 // with lowest integer conversion rank (4.13) greater than the rank of long
1247 // long in which all the values of the enumeration can be represented. If
1248 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001249 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1250 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1251 // provided for a scoped enumeration.
1252 if (FromEnumType->getDecl()->isScoped())
1253 return false;
1254
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001255 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001256 if (ToType->isIntegerType() &&
1257 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001258 return Context.hasSameUnqualifiedType(ToType,
1259 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001260 }
John McCall56774992009-12-09 09:09:27 +00001261
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001262 // C++0x [conv.prom]p2:
1263 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1264 // to an rvalue a prvalue of the first of the following types that can
1265 // represent all the values of its underlying type: int, unsigned int,
1266 // long int, unsigned long int, long long int, or unsigned long long int.
1267 // If none of the types in that list can represent all the values of its
1268 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1269 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1270 // type.
1271 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1272 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001273 // Determine whether the type we're converting from is signed or
1274 // unsigned.
1275 bool FromIsSigned;
1276 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001277
1278 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1279 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001280
1281 // The types we'll try to promote to, in the appropriate
1282 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001283 QualType PromoteTypes[6] = {
1284 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001285 Context.LongTy, Context.UnsignedLongTy ,
1286 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001287 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001288 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001289 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1290 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001291 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001292 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1293 // We found the type that we can promote to. If this is the
1294 // type we wanted, we have a promotion. Otherwise, no
1295 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001296 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297 }
1298 }
1299 }
1300
1301 // An rvalue for an integral bit-field (9.6) can be converted to an
1302 // rvalue of type int if int can represent all the values of the
1303 // bit-field; otherwise, it can be converted to unsigned int if
1304 // unsigned int can represent all the values of the bit-field. If
1305 // the bit-field is larger yet, no integral promotion applies to
1306 // it. If the bit-field has an enumerated type, it is treated as any
1307 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001308 // FIXME: We should delay checking of bit-fields until we actually perform the
1309 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001310 using llvm::APSInt;
1311 if (From)
1312 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001313 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001314 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001315 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1316 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1317 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001318
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001319 // Are we promoting to an int from a bitfield that fits in an int?
1320 if (BitWidth < ToSize ||
1321 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1322 return To->getKind() == BuiltinType::Int;
1323 }
Mike Stump11289f42009-09-09 15:08:12 +00001324
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001325 // Are we promoting to an unsigned int from an unsigned bitfield
1326 // that fits into an unsigned int?
1327 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1328 return To->getKind() == BuiltinType::UInt;
1329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001331 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001332 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001333 }
Mike Stump11289f42009-09-09 15:08:12 +00001334
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001335 // An rvalue of type bool can be converted to an rvalue of type int,
1336 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001337 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001338 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001339 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001340
1341 return false;
1342}
1343
1344/// IsFloatingPointPromotion - Determines whether the conversion from
1345/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1346/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001347bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001348 /// An rvalue of type float can be converted to an rvalue of type
1349 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001350 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1351 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001352 if (FromBuiltin->getKind() == BuiltinType::Float &&
1353 ToBuiltin->getKind() == BuiltinType::Double)
1354 return true;
1355
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001356 // C99 6.3.1.5p1:
1357 // When a float is promoted to double or long double, or a
1358 // double is promoted to long double [...].
1359 if (!getLangOptions().CPlusPlus &&
1360 (FromBuiltin->getKind() == BuiltinType::Float ||
1361 FromBuiltin->getKind() == BuiltinType::Double) &&
1362 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1363 return true;
1364 }
1365
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001366 return false;
1367}
1368
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001369/// \brief Determine if a conversion is a complex promotion.
1370///
1371/// A complex promotion is defined as a complex -> complex conversion
1372/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001373/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001374bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001375 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001376 if (!FromComplex)
1377 return false;
1378
John McCall9dd450b2009-09-21 23:43:11 +00001379 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001380 if (!ToComplex)
1381 return false;
1382
1383 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001384 ToComplex->getElementType()) ||
1385 IsIntegralPromotion(0, FromComplex->getElementType(),
1386 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001387}
1388
Douglas Gregor237f96c2008-11-26 23:31:11 +00001389/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1390/// the pointer type FromPtr to a pointer to type ToPointee, with the
1391/// same type qualifiers as FromPtr has on its pointee type. ToType,
1392/// if non-empty, will be a pointer to ToType that may or may not have
1393/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001394static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001395BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001396 QualType ToPointee, QualType ToType,
1397 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001398 assert((FromPtr->getTypeClass() == Type::Pointer ||
1399 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1400 "Invalid similarly-qualified pointer type");
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001401
1402 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1403 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1404 return ToType.getUnqualifiedType();
1405
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001406 QualType CanonFromPointee
1407 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001408 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001409 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001410
1411 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001412 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001413 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001414 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001415 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001416
1417 // Build a pointer to ToPointee. It has the right qualifiers
1418 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001419 if (isa<ObjCObjectPointerType>(ToType))
1420 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001421 return Context.getPointerType(ToPointee);
1422 }
1423
1424 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001425 QualType QualifiedCanonToPointee
1426 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001427
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001428 if (isa<ObjCObjectPointerType>(ToType))
1429 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1430 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001431}
1432
Mike Stump11289f42009-09-09 15:08:12 +00001433static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001434 bool InOverloadResolution,
1435 ASTContext &Context) {
1436 // Handle value-dependent integral null pointer constants correctly.
1437 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1438 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001439 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001440 return !InOverloadResolution;
1441
Douglas Gregor56751b52009-09-25 04:25:58 +00001442 return Expr->isNullPointerConstant(Context,
1443 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1444 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001445}
Mike Stump11289f42009-09-09 15:08:12 +00001446
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001447/// IsPointerConversion - Determines whether the conversion of the
1448/// expression From, which has the (possibly adjusted) type FromType,
1449/// can be converted to the type ToType via a pointer conversion (C++
1450/// 4.10). If so, returns true and places the converted type (that
1451/// might differ from ToType in its cv-qualifiers at some level) into
1452/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001453///
Douglas Gregora29dc052008-11-27 01:19:21 +00001454/// This routine also supports conversions to and from block pointers
1455/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1456/// pointers to interfaces. FIXME: Once we've determined the
1457/// appropriate overloading rules for Objective-C, we may want to
1458/// split the Objective-C checks into a different routine; however,
1459/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001460/// conversions, so for now they live here. IncompatibleObjC will be
1461/// set if the conversion is an allowed Objective-C conversion that
1462/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001463bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001464 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001465 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001466 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001467 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001468 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1469 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001470 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001471
Mike Stump11289f42009-09-09 15:08:12 +00001472 // Conversion from a null pointer constant to any Objective-C pointer type.
1473 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001474 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001475 ConvertedType = ToType;
1476 return true;
1477 }
1478
Douglas Gregor231d1c62008-11-27 00:15:41 +00001479 // Blocks: Block pointers can be converted to void*.
1480 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001481 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001482 ConvertedType = ToType;
1483 return true;
1484 }
1485 // Blocks: A null pointer constant can be converted to a block
1486 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001487 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001488 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001489 ConvertedType = ToType;
1490 return true;
1491 }
1492
Sebastian Redl576fd422009-05-10 18:38:11 +00001493 // If the left-hand-side is nullptr_t, the right side can be a null
1494 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001495 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001496 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001497 ConvertedType = ToType;
1498 return true;
1499 }
1500
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001501 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001502 if (!ToTypePtr)
1503 return false;
1504
1505 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001506 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001507 ConvertedType = ToType;
1508 return true;
1509 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001510
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001511 // Beyond this point, both types need to be pointers
1512 // , including objective-c pointers.
1513 QualType ToPointeeType = ToTypePtr->getPointeeType();
1514 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001515 ConvertedType = BuildSimilarlyQualifiedPointerType(
1516 FromType->getAs<ObjCObjectPointerType>(),
1517 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001518 ToType, Context);
1519 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001520 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001521 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001522 if (!FromTypePtr)
1523 return false;
1524
1525 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001526
Douglas Gregorfb640862010-08-18 21:25:30 +00001527 // If the unqualified pointee types are the same, this can't be a
1528 // pointer conversion, so don't do all of the work below.
1529 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1530 return false;
1531
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001532 // An rvalue of type "pointer to cv T," where T is an object type,
1533 // can be converted to an rvalue of type "pointer to cv void" (C++
1534 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001535 if (FromPointeeType->isIncompleteOrObjectType() &&
1536 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001537 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001538 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001539 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001540 return true;
1541 }
1542
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001543 // When we're overloading in C, we allow a special kind of pointer
1544 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001545 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001546 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001547 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001548 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001549 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001550 return true;
1551 }
1552
Douglas Gregor5c407d92008-10-23 00:40:37 +00001553 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001554 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001555 // An rvalue of type "pointer to cv D," where D is a class type,
1556 // can be converted to an rvalue of type "pointer to cv B," where
1557 // B is a base class (clause 10) of D. If B is an inaccessible
1558 // (clause 11) or ambiguous (10.2) base class of D, a program that
1559 // necessitates this conversion is ill-formed. The result of the
1560 // conversion is a pointer to the base class sub-object of the
1561 // derived class object. The null pointer value is converted to
1562 // the null pointer value of the destination type.
1563 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001564 // Note that we do not check for ambiguity or inaccessibility
1565 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001566 if (getLangOptions().CPlusPlus &&
1567 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001568 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001569 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001570 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001571 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001572 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001573 ToType, Context);
1574 return true;
1575 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001576
Douglas Gregora119f102008-12-19 19:13:09 +00001577 return false;
1578}
1579
1580/// isObjCPointerConversion - Determines whether this is an
1581/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1582/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001583bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001584 QualType& ConvertedType,
1585 bool &IncompatibleObjC) {
1586 if (!getLangOptions().ObjC1)
1587 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001588
Steve Naroff7cae42b2009-07-10 23:34:53 +00001589 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001590 const ObjCObjectPointerType* ToObjCPtr =
1591 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001592 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001593 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001594
Steve Naroff7cae42b2009-07-10 23:34:53 +00001595 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001596 // If the pointee types are the same (ignoring qualifications),
1597 // then this is not a pointer conversion.
1598 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1599 FromObjCPtr->getPointeeType()))
1600 return false;
1601
Steve Naroff1329fa02009-07-15 18:40:39 +00001602 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001603 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001604 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001605 ConvertedType = ToType;
1606 return true;
1607 }
1608 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001609 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001610 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001611 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001612 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001613 ConvertedType = ToType;
1614 return true;
1615 }
1616 // Objective C++: We're able to convert from a pointer to an
1617 // interface to a pointer to a different interface.
1618 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001619 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1620 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1621 if (getLangOptions().CPlusPlus && LHS && RHS &&
1622 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1623 FromObjCPtr->getPointeeType()))
1624 return false;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001625 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1626 ToObjCPtr->getPointeeType(),
1627 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001628 return true;
1629 }
1630
1631 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1632 // Okay: this is some kind of implicit downcast of Objective-C
1633 // interfaces, which is permitted. However, we're going to
1634 // complain about it.
1635 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001636 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1637 ToObjCPtr->getPointeeType(),
1638 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001639 return true;
1640 }
Mike Stump11289f42009-09-09 15:08:12 +00001641 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001642 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001643 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001644 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001645 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001646 else if (const BlockPointerType *ToBlockPtr =
1647 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001648 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001649 // to a block pointer type.
1650 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1651 ConvertedType = ToType;
1652 return true;
1653 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001654 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001655 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001656 else if (FromType->getAs<BlockPointerType>() &&
1657 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1658 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001659 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001660 ConvertedType = ToType;
1661 return true;
1662 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001663 else
Douglas Gregora119f102008-12-19 19:13:09 +00001664 return false;
1665
Douglas Gregor033f56d2008-12-23 00:53:59 +00001666 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001667 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001668 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001669 else if (const BlockPointerType *FromBlockPtr =
1670 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001671 FromPointeeType = FromBlockPtr->getPointeeType();
1672 else
Douglas Gregora119f102008-12-19 19:13:09 +00001673 return false;
1674
Douglas Gregora119f102008-12-19 19:13:09 +00001675 // If we have pointers to pointers, recursively check whether this
1676 // is an Objective-C conversion.
1677 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1678 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1679 IncompatibleObjC)) {
1680 // We always complain about this conversion.
1681 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001682 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001683 return true;
1684 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001685 // Allow conversion of pointee being objective-c pointer to another one;
1686 // as in I* to id.
1687 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1688 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1689 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1690 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001691 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001692 return true;
1693 }
1694
Douglas Gregor033f56d2008-12-23 00:53:59 +00001695 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001696 // differences in the argument and result types are in Objective-C
1697 // pointer conversions. If so, we permit the conversion (but
1698 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001699 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001700 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001701 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001702 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001703 if (FromFunctionType && ToFunctionType) {
1704 // If the function types are exactly the same, this isn't an
1705 // Objective-C pointer conversion.
1706 if (Context.getCanonicalType(FromPointeeType)
1707 == Context.getCanonicalType(ToPointeeType))
1708 return false;
1709
1710 // Perform the quick checks that will tell us whether these
1711 // function types are obviously different.
1712 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1713 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1714 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1715 return false;
1716
1717 bool HasObjCConversion = false;
1718 if (Context.getCanonicalType(FromFunctionType->getResultType())
1719 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1720 // Okay, the types match exactly. Nothing to do.
1721 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1722 ToFunctionType->getResultType(),
1723 ConvertedType, IncompatibleObjC)) {
1724 // Okay, we have an Objective-C pointer conversion.
1725 HasObjCConversion = true;
1726 } else {
1727 // Function types are too different. Abort.
1728 return false;
1729 }
Mike Stump11289f42009-09-09 15:08:12 +00001730
Douglas Gregora119f102008-12-19 19:13:09 +00001731 // Check argument types.
1732 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1733 ArgIdx != NumArgs; ++ArgIdx) {
1734 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1735 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1736 if (Context.getCanonicalType(FromArgType)
1737 == Context.getCanonicalType(ToArgType)) {
1738 // Okay, the types match exactly. Nothing to do.
1739 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1740 ConvertedType, IncompatibleObjC)) {
1741 // Okay, we have an Objective-C pointer conversion.
1742 HasObjCConversion = true;
1743 } else {
1744 // Argument types are too different. Abort.
1745 return false;
1746 }
1747 }
1748
1749 if (HasObjCConversion) {
1750 // We had an Objective-C conversion. Allow this pointer
1751 // conversion, but complain about it.
1752 ConvertedType = ToType;
1753 IncompatibleObjC = true;
1754 return true;
1755 }
1756 }
1757
Sebastian Redl72b597d2009-01-25 19:43:20 +00001758 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001759}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001760
1761/// FunctionArgTypesAreEqual - This routine checks two function proto types
1762/// for equlity of their argument types. Caller has already checked that
1763/// they have same number of arguments. This routine assumes that Objective-C
1764/// pointer types which only differ in their protocol qualifiers are equal.
John McCall424cec92011-01-19 06:33:43 +00001765bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1766 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001767 if (!getLangOptions().ObjC1)
1768 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1769 NewType->arg_type_begin());
1770
1771 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1772 N = NewType->arg_type_begin(),
1773 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1774 QualType ToType = (*O);
1775 QualType FromType = (*N);
1776 if (ToType != FromType) {
1777 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1778 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001779 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1780 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1781 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1782 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001783 continue;
1784 }
John McCall8b07ec22010-05-15 11:32:37 +00001785 else if (const ObjCObjectPointerType *PTTo =
1786 ToType->getAs<ObjCObjectPointerType>()) {
1787 if (const ObjCObjectPointerType *PTFr =
1788 FromType->getAs<ObjCObjectPointerType>())
1789 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1790 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001791 }
1792 return false;
1793 }
1794 }
1795 return true;
1796}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001797
Douglas Gregor39c16d42008-10-24 04:54:22 +00001798/// CheckPointerConversion - Check the pointer conversion from the
1799/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001800/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001801/// conversions for which IsPointerConversion has already returned
1802/// true. It returns true and produces a diagnostic if there was an
1803/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001804bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001805 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001806 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001807 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001808 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001809 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001810
John McCall8cb679e2010-11-15 09:13:47 +00001811 Kind = CK_BitCast;
1812
Douglas Gregor4038cf42010-06-08 17:35:15 +00001813 if (CXXBoolLiteralExpr* LitBool
1814 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001815 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001816 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1817 << ToType;
1818
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001819 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1820 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001821 QualType FromPointeeType = FromPtrType->getPointeeType(),
1822 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001823
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001824 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1825 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001826 // We must have a derived-to-base conversion. Check an
1827 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001828 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1829 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001830 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001831 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001832 return true;
1833
1834 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001835 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001836 }
1837 }
Mike Stump11289f42009-09-09 15:08:12 +00001838 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001839 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001840 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001841 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001842 // Objective-C++ conversions are always okay.
1843 // FIXME: We should have a different class of conversions for the
1844 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001845 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001846 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001847 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001848 }
John McCall8cb679e2010-11-15 09:13:47 +00001849
1850 // We shouldn't fall into this case unless it's valid for other
1851 // reasons.
1852 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1853 Kind = CK_NullToPointer;
1854
Douglas Gregor39c16d42008-10-24 04:54:22 +00001855 return false;
1856}
1857
Sebastian Redl72b597d2009-01-25 19:43:20 +00001858/// IsMemberPointerConversion - Determines whether the conversion of the
1859/// expression From, which has the (possibly adjusted) type FromType, can be
1860/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1861/// If so, returns true and places the converted type (that might differ from
1862/// ToType in its cv-qualifiers at some level) into ConvertedType.
1863bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001864 QualType ToType,
1865 bool InOverloadResolution,
1866 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001867 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001868 if (!ToTypePtr)
1869 return false;
1870
1871 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001872 if (From->isNullPointerConstant(Context,
1873 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1874 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001875 ConvertedType = ToType;
1876 return true;
1877 }
1878
1879 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001880 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001881 if (!FromTypePtr)
1882 return false;
1883
1884 // A pointer to member of B can be converted to a pointer to member of D,
1885 // where D is derived from B (C++ 4.11p2).
1886 QualType FromClass(FromTypePtr->getClass(), 0);
1887 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001888
Douglas Gregor7f6ae692010-12-21 21:40:41 +00001889 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
1890 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
1891 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001892 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1893 ToClass.getTypePtr());
1894 return true;
1895 }
1896
1897 return false;
1898}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001899
Sebastian Redl72b597d2009-01-25 19:43:20 +00001900/// CheckMemberPointerConversion - Check the member pointer conversion from the
1901/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001902/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001903/// for which IsMemberPointerConversion has already returned true. It returns
1904/// true and produces a diagnostic if there was an error, or returns false
1905/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001906bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001907 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001908 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001909 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001910 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001911 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001912 if (!FromPtrType) {
1913 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001914 assert(From->isNullPointerConstant(Context,
1915 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001916 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001917 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001918 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001919 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001920
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001921 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001922 assert(ToPtrType && "No member pointer cast has a target type "
1923 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001924
Sebastian Redled8f2002009-01-28 18:33:18 +00001925 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1926 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001927
Sebastian Redled8f2002009-01-28 18:33:18 +00001928 // FIXME: What about dependent types?
1929 assert(FromClass->isRecordType() && "Pointer into non-class.");
1930 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001931
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001932 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001933 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001934 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1935 assert(DerivationOkay &&
1936 "Should not have been called if derivation isn't OK.");
1937 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001938
Sebastian Redled8f2002009-01-28 18:33:18 +00001939 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1940 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001941 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1942 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1943 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1944 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001945 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001946
Douglas Gregor89ee6822009-02-28 01:32:25 +00001947 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001948 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1949 << FromClass << ToClass << QualType(VBase, 0)
1950 << From->getSourceRange();
1951 return true;
1952 }
1953
John McCall5b0829a2010-02-10 09:31:12 +00001954 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001955 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1956 Paths.front(),
1957 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001958
Anders Carlssond7923c62009-08-22 23:33:40 +00001959 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001960 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001961 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001962 return false;
1963}
1964
Douglas Gregor9a657932008-10-21 23:43:52 +00001965/// IsQualificationConversion - Determines whether the conversion from
1966/// an rvalue of type FromType to ToType is a qualification conversion
1967/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001968bool
1969Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001970 FromType = Context.getCanonicalType(FromType);
1971 ToType = Context.getCanonicalType(ToType);
1972
1973 // If FromType and ToType are the same type, this is not a
1974 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001975 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001976 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001977
Douglas Gregor9a657932008-10-21 23:43:52 +00001978 // (C++ 4.4p4):
1979 // A conversion can add cv-qualifiers at levels other than the first
1980 // in multi-level pointers, subject to the following rules: [...]
1981 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001982 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001983 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001984 // Within each iteration of the loop, we check the qualifiers to
1985 // determine if this still looks like a qualification
1986 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001987 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001988 // until there are no more pointers or pointers-to-members left to
1989 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001990 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001991
1992 // -- for every j > 0, if const is in cv 1,j then const is in cv
1993 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001994 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001995 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001996
Douglas Gregor9a657932008-10-21 23:43:52 +00001997 // -- if the cv 1,j and cv 2,j are different, then const is in
1998 // every cv for 0 < k < j.
1999 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002000 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002001 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002002
Douglas Gregor9a657932008-10-21 23:43:52 +00002003 // Keep track of whether all prior cv-qualifiers in the "to" type
2004 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002005 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002006 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002007 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002008
2009 // We are left with FromType and ToType being the pointee types
2010 // after unwrapping the original FromType and ToType the same number
2011 // of types. If we unwrapped any pointers, and if FromType and
2012 // ToType have the same unqualified type (since we checked
2013 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002014 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002015}
2016
Douglas Gregor576e98c2009-01-30 23:27:23 +00002017/// Determines whether there is a user-defined conversion sequence
2018/// (C++ [over.ics.user]) that converts expression From to the type
2019/// ToType. If such a conversion exists, User will contain the
2020/// user-defined conversion sequence that performs such a conversion
2021/// and this routine will return true. Otherwise, this routine returns
2022/// false and User is unspecified.
2023///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002024/// \param AllowExplicit true if the conversion should consider C++0x
2025/// "explicit" conversion functions as well as non-explicit conversion
2026/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002027static OverloadingResult
2028IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2029 UserDefinedConversionSequence& User,
2030 OverloadCandidateSet& CandidateSet,
2031 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002032 // Whether we will only visit constructors.
2033 bool ConstructorsOnly = false;
2034
2035 // If the type we are conversion to is a class type, enumerate its
2036 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002037 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002038 // C++ [over.match.ctor]p1:
2039 // When objects of class type are direct-initialized (8.5), or
2040 // copy-initialized from an expression of the same or a
2041 // derived class type (8.5), overload resolution selects the
2042 // constructor. [...] For copy-initialization, the candidate
2043 // functions are all the converting constructors (12.3.1) of
2044 // that class. The argument list is the expression-list within
2045 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002046 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002047 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002048 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002049 ConstructorsOnly = true;
2050
John McCall5c32be02010-08-24 20:38:10 +00002051 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002052 // We're not going to find any constructors.
2053 } else if (CXXRecordDecl *ToRecordDecl
2054 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002055 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002056 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002057 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002058 NamedDecl *D = *Con;
2059 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2060
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002061 // Find the constructor (which may be a template).
2062 CXXConstructorDecl *Constructor = 0;
2063 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002064 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002065 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002066 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002067 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2068 else
John McCalla0296f72010-03-19 07:35:19 +00002069 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002070
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002071 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002072 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002073 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002074 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2075 /*ExplicitArgs*/ 0,
2076 &From, 1, CandidateSet,
2077 /*SuppressUserConversions=*/
2078 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002079 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002080 // Allow one user-defined conversion when user specifies a
2081 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002082 S.AddOverloadCandidate(Constructor, FoundDecl,
2083 &From, 1, CandidateSet,
2084 /*SuppressUserConversions=*/
2085 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002086 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002087 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002088 }
2089 }
2090
Douglas Gregor5ab11652010-04-17 22:01:05 +00002091 // Enumerate conversion functions, if we're allowed to.
2092 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002093 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2094 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002095 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002096 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002097 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002098 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002099 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2100 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002101 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002102 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002103 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002104 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002105 DeclAccessPair FoundDecl = I.getPair();
2106 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002107 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2108 if (isa<UsingShadowDecl>(D))
2109 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2110
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002111 CXXConversionDecl *Conv;
2112 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002113 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2114 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002115 else
John McCallda4458e2010-03-31 01:36:47 +00002116 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002117
2118 if (AllowExplicit || !Conv->isExplicit()) {
2119 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002120 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2121 ActingContext, From, ToType,
2122 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002123 else
John McCall5c32be02010-08-24 20:38:10 +00002124 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2125 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002126 }
2127 }
2128 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002129 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002130
2131 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002132 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002133 case OR_Success:
2134 // Record the standard conversion we used and the conversion function.
2135 if (CXXConstructorDecl *Constructor
2136 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2137 // C++ [over.ics.user]p1:
2138 // If the user-defined conversion is specified by a
2139 // constructor (12.3.1), the initial standard conversion
2140 // sequence converts the source type to the type required by
2141 // the argument of the constructor.
2142 //
2143 QualType ThisType = Constructor->getThisType(S.Context);
2144 if (Best->Conversions[0].isEllipsis())
2145 User.EllipsisConversion = true;
2146 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002147 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002148 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002149 }
John McCall5c32be02010-08-24 20:38:10 +00002150 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002151 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002152 User.After.setAsIdentityConversion();
2153 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2154 User.After.setAllToTypes(ToType);
2155 return OR_Success;
2156 } else if (CXXConversionDecl *Conversion
2157 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2158 // C++ [over.ics.user]p1:
2159 //
2160 // [...] If the user-defined conversion is specified by a
2161 // conversion function (12.3.2), the initial standard
2162 // conversion sequence converts the source type to the
2163 // implicit object parameter of the conversion function.
2164 User.Before = Best->Conversions[0].Standard;
2165 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002166 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002167 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002168
John McCall5c32be02010-08-24 20:38:10 +00002169 // C++ [over.ics.user]p2:
2170 // The second standard conversion sequence converts the
2171 // result of the user-defined conversion to the target type
2172 // for the sequence. Since an implicit conversion sequence
2173 // is an initialization, the special rules for
2174 // initialization by user-defined conversion apply when
2175 // selecting the best user-defined conversion for a
2176 // user-defined conversion sequence (see 13.3.3 and
2177 // 13.3.3.1).
2178 User.After = Best->FinalConversion;
2179 return OR_Success;
2180 } else {
2181 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002182 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002183 }
2184
John McCall5c32be02010-08-24 20:38:10 +00002185 case OR_No_Viable_Function:
2186 return OR_No_Viable_Function;
2187 case OR_Deleted:
2188 // No conversion here! We're done.
2189 return OR_Deleted;
2190
2191 case OR_Ambiguous:
2192 return OR_Ambiguous;
2193 }
2194
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002195 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002196}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002197
2198bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002199Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002200 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002201 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002202 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002203 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002204 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002205 if (OvResult == OR_Ambiguous)
2206 Diag(From->getSourceRange().getBegin(),
2207 diag::err_typecheck_ambiguous_condition)
2208 << From->getType() << ToType << From->getSourceRange();
2209 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2210 Diag(From->getSourceRange().getBegin(),
2211 diag::err_typecheck_nonviable_condition)
2212 << From->getType() << ToType << From->getSourceRange();
2213 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002214 return false;
John McCall5c32be02010-08-24 20:38:10 +00002215 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002216 return true;
2217}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002218
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002219/// CompareImplicitConversionSequences - Compare two implicit
2220/// conversion sequences to determine whether one is better than the
2221/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002222static ImplicitConversionSequence::CompareKind
2223CompareImplicitConversionSequences(Sema &S,
2224 const ImplicitConversionSequence& ICS1,
2225 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002226{
2227 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2228 // conversion sequences (as defined in 13.3.3.1)
2229 // -- a standard conversion sequence (13.3.3.1.1) is a better
2230 // conversion sequence than a user-defined conversion sequence or
2231 // an ellipsis conversion sequence, and
2232 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2233 // conversion sequence than an ellipsis conversion sequence
2234 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002235 //
John McCall0d1da222010-01-12 00:44:57 +00002236 // C++0x [over.best.ics]p10:
2237 // For the purpose of ranking implicit conversion sequences as
2238 // described in 13.3.3.2, the ambiguous conversion sequence is
2239 // treated as a user-defined sequence that is indistinguishable
2240 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002241 if (ICS1.getKindRank() < ICS2.getKindRank())
2242 return ImplicitConversionSequence::Better;
2243 else if (ICS2.getKindRank() < ICS1.getKindRank())
2244 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002245
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002246 // The following checks require both conversion sequences to be of
2247 // the same kind.
2248 if (ICS1.getKind() != ICS2.getKind())
2249 return ImplicitConversionSequence::Indistinguishable;
2250
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002251 // Two implicit conversion sequences of the same form are
2252 // indistinguishable conversion sequences unless one of the
2253 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002254 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002255 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002256 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002257 // User-defined conversion sequence U1 is a better conversion
2258 // sequence than another user-defined conversion sequence U2 if
2259 // they contain the same user-defined conversion function or
2260 // constructor and if the second standard conversion sequence of
2261 // U1 is better than the second standard conversion sequence of
2262 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002263 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002264 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002265 return CompareStandardConversionSequences(S,
2266 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002267 ICS2.UserDefined.After);
2268 }
2269
2270 return ImplicitConversionSequence::Indistinguishable;
2271}
2272
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002273static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2274 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2275 Qualifiers Quals;
2276 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2277 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2278 }
2279
2280 return Context.hasSameUnqualifiedType(T1, T2);
2281}
2282
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002283// Per 13.3.3.2p3, compare the given standard conversion sequences to
2284// determine if one is a proper subset of the other.
2285static ImplicitConversionSequence::CompareKind
2286compareStandardConversionSubsets(ASTContext &Context,
2287 const StandardConversionSequence& SCS1,
2288 const StandardConversionSequence& SCS2) {
2289 ImplicitConversionSequence::CompareKind Result
2290 = ImplicitConversionSequence::Indistinguishable;
2291
Douglas Gregore87561a2010-05-23 22:10:15 +00002292 // the identity conversion sequence is considered to be a subsequence of
2293 // any non-identity conversion sequence
2294 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2295 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2296 return ImplicitConversionSequence::Better;
2297 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2298 return ImplicitConversionSequence::Worse;
2299 }
2300
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002301 if (SCS1.Second != SCS2.Second) {
2302 if (SCS1.Second == ICK_Identity)
2303 Result = ImplicitConversionSequence::Better;
2304 else if (SCS2.Second == ICK_Identity)
2305 Result = ImplicitConversionSequence::Worse;
2306 else
2307 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002308 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002309 return ImplicitConversionSequence::Indistinguishable;
2310
2311 if (SCS1.Third == SCS2.Third) {
2312 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2313 : ImplicitConversionSequence::Indistinguishable;
2314 }
2315
2316 if (SCS1.Third == ICK_Identity)
2317 return Result == ImplicitConversionSequence::Worse
2318 ? ImplicitConversionSequence::Indistinguishable
2319 : ImplicitConversionSequence::Better;
2320
2321 if (SCS2.Third == ICK_Identity)
2322 return Result == ImplicitConversionSequence::Better
2323 ? ImplicitConversionSequence::Indistinguishable
2324 : ImplicitConversionSequence::Worse;
2325
2326 return ImplicitConversionSequence::Indistinguishable;
2327}
2328
Douglas Gregore696ebb2011-01-26 14:52:12 +00002329/// \brief Determine whether one of the given reference bindings is better
2330/// than the other based on what kind of bindings they are.
2331static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2332 const StandardConversionSequence &SCS2) {
2333 // C++0x [over.ics.rank]p3b4:
2334 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2335 // implicit object parameter of a non-static member function declared
2336 // without a ref-qualifier, and *either* S1 binds an rvalue reference
2337 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
2338 // lvalue reference to a function lvalue and S2 binds an rvalue
2339 // reference*.
2340 //
2341 // FIXME: Rvalue references. We're going rogue with the above edits,
2342 // because the semantics in the current C++0x working paper (N3225 at the
2343 // time of this writing) break the standard definition of std::forward
2344 // and std::reference_wrapper when dealing with references to functions.
2345 // Proposed wording changes submitted to CWG for consideration.
2346 //
2347 // FIXME: Rvalue references. We don't know if we're dealing with the
2348 // implicit object parameter, or if the member function in this case has a
2349 // ref qualifier. (Of course, we don't have ref qualifiers yet.)
2350 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2351 SCS2.IsLvalueReference) ||
2352 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2353 !SCS2.IsLvalueReference);
2354}
2355
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002356/// CompareStandardConversionSequences - Compare two standard
2357/// conversion sequences to determine whether one is better than the
2358/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002359static ImplicitConversionSequence::CompareKind
2360CompareStandardConversionSequences(Sema &S,
2361 const StandardConversionSequence& SCS1,
2362 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002363{
2364 // Standard conversion sequence S1 is a better conversion sequence
2365 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2366
2367 // -- S1 is a proper subsequence of S2 (comparing the conversion
2368 // sequences in the canonical form defined by 13.3.3.1.1,
2369 // excluding any Lvalue Transformation; the identity conversion
2370 // sequence is considered to be a subsequence of any
2371 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002372 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002373 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002374 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002375
2376 // -- the rank of S1 is better than the rank of S2 (by the rules
2377 // defined below), or, if not that,
2378 ImplicitConversionRank Rank1 = SCS1.getRank();
2379 ImplicitConversionRank Rank2 = SCS2.getRank();
2380 if (Rank1 < Rank2)
2381 return ImplicitConversionSequence::Better;
2382 else if (Rank2 < Rank1)
2383 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002384
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002385 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2386 // are indistinguishable unless one of the following rules
2387 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002388
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002389 // A conversion that is not a conversion of a pointer, or
2390 // pointer to member, to bool is better than another conversion
2391 // that is such a conversion.
2392 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2393 return SCS2.isPointerConversionToBool()
2394 ? ImplicitConversionSequence::Better
2395 : ImplicitConversionSequence::Worse;
2396
Douglas Gregor5c407d92008-10-23 00:40:37 +00002397 // C++ [over.ics.rank]p4b2:
2398 //
2399 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002400 // conversion of B* to A* is better than conversion of B* to
2401 // void*, and conversion of A* to void* is better than conversion
2402 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002403 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002404 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002405 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002406 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002407 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2408 // Exactly one of the conversion sequences is a conversion to
2409 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002410 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2411 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002412 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2413 // Neither conversion sequence converts to a void pointer; compare
2414 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002415 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002416 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002417 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002418 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2419 // Both conversion sequences are conversions to void
2420 // pointers. Compare the source types to determine if there's an
2421 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002422 QualType FromType1 = SCS1.getFromType();
2423 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002424
2425 // Adjust the types we're converting from via the array-to-pointer
2426 // conversion, if we need to.
2427 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002428 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002429 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002430 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002431
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002432 QualType FromPointee1
2433 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2434 QualType FromPointee2
2435 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002436
John McCall5c32be02010-08-24 20:38:10 +00002437 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002438 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002439 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002440 return ImplicitConversionSequence::Worse;
2441
2442 // Objective-C++: If one interface is more specific than the
2443 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002444 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2445 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002446 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002447 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002448 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002449 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002450 return ImplicitConversionSequence::Worse;
2451 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002452 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002453
2454 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2455 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002456 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002457 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002458 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002459
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002460 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002461 // Check for a better reference binding based on the kind of bindings.
2462 if (isBetterReferenceBindingKind(SCS1, SCS2))
2463 return ImplicitConversionSequence::Better;
2464 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2465 return ImplicitConversionSequence::Worse;
2466
Sebastian Redlb28b4072009-03-22 23:49:27 +00002467 // C++ [over.ics.rank]p3b4:
2468 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2469 // which the references refer are the same type except for
2470 // top-level cv-qualifiers, and the type to which the reference
2471 // initialized by S2 refers is more cv-qualified than the type
2472 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002473 QualType T1 = SCS1.getToType(2);
2474 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002475 T1 = S.Context.getCanonicalType(T1);
2476 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002477 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002478 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2479 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002480 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002481 // If the type is an array type, promote the element qualifiers to the
2482 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002483 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002484 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002485 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002486 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002487 if (T2.isMoreQualifiedThan(T1))
2488 return ImplicitConversionSequence::Better;
2489 else if (T1.isMoreQualifiedThan(T2))
2490 return ImplicitConversionSequence::Worse;
2491 }
2492 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002493
2494 return ImplicitConversionSequence::Indistinguishable;
2495}
2496
2497/// CompareQualificationConversions - Compares two standard conversion
2498/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002499/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2500ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002501CompareQualificationConversions(Sema &S,
2502 const StandardConversionSequence& SCS1,
2503 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002504 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002505 // -- S1 and S2 differ only in their qualification conversion and
2506 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2507 // cv-qualification signature of type T1 is a proper subset of
2508 // the cv-qualification signature of type T2, and S1 is not the
2509 // deprecated string literal array-to-pointer conversion (4.2).
2510 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2511 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2512 return ImplicitConversionSequence::Indistinguishable;
2513
2514 // FIXME: the example in the standard doesn't use a qualification
2515 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002516 QualType T1 = SCS1.getToType(2);
2517 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002518 T1 = S.Context.getCanonicalType(T1);
2519 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002520 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002521 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2522 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002523
2524 // If the types are the same, we won't learn anything by unwrapped
2525 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002526 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002527 return ImplicitConversionSequence::Indistinguishable;
2528
Chandler Carruth607f38e2009-12-29 07:16:59 +00002529 // If the type is an array type, promote the element qualifiers to the type
2530 // for comparison.
2531 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002532 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002533 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002534 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002535
Mike Stump11289f42009-09-09 15:08:12 +00002536 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002537 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002538 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002539 // Within each iteration of the loop, we check the qualifiers to
2540 // determine if this still looks like a qualification
2541 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002542 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002543 // until there are no more pointers or pointers-to-members left
2544 // to unwrap. This essentially mimics what
2545 // IsQualificationConversion does, but here we're checking for a
2546 // strict subset of qualifiers.
2547 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2548 // The qualifiers are the same, so this doesn't tell us anything
2549 // about how the sequences rank.
2550 ;
2551 else if (T2.isMoreQualifiedThan(T1)) {
2552 // T1 has fewer qualifiers, so it could be the better sequence.
2553 if (Result == ImplicitConversionSequence::Worse)
2554 // Neither has qualifiers that are a subset of the other's
2555 // qualifiers.
2556 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002557
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002558 Result = ImplicitConversionSequence::Better;
2559 } else if (T1.isMoreQualifiedThan(T2)) {
2560 // T2 has fewer qualifiers, so it could be the better sequence.
2561 if (Result == ImplicitConversionSequence::Better)
2562 // Neither has qualifiers that are a subset of the other's
2563 // qualifiers.
2564 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002565
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002566 Result = ImplicitConversionSequence::Worse;
2567 } else {
2568 // Qualifiers are disjoint.
2569 return ImplicitConversionSequence::Indistinguishable;
2570 }
2571
2572 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002573 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002574 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002575 }
2576
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002577 // Check that the winning standard conversion sequence isn't using
2578 // the deprecated string literal array to pointer conversion.
2579 switch (Result) {
2580 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002581 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002582 Result = ImplicitConversionSequence::Indistinguishable;
2583 break;
2584
2585 case ImplicitConversionSequence::Indistinguishable:
2586 break;
2587
2588 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002589 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002590 Result = ImplicitConversionSequence::Indistinguishable;
2591 break;
2592 }
2593
2594 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002595}
2596
Douglas Gregor5c407d92008-10-23 00:40:37 +00002597/// CompareDerivedToBaseConversions - Compares two standard conversion
2598/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002599/// various kinds of derived-to-base conversions (C++
2600/// [over.ics.rank]p4b3). As part of these checks, we also look at
2601/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002602ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002603CompareDerivedToBaseConversions(Sema &S,
2604 const StandardConversionSequence& SCS1,
2605 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002606 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002607 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002608 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002609 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002610
2611 // Adjust the types we're converting from via the array-to-pointer
2612 // conversion, if we need to.
2613 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002614 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002615 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002616 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002617
2618 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002619 FromType1 = S.Context.getCanonicalType(FromType1);
2620 ToType1 = S.Context.getCanonicalType(ToType1);
2621 FromType2 = S.Context.getCanonicalType(FromType2);
2622 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002623
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002624 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002625 //
2626 // If class B is derived directly or indirectly from class A and
2627 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002628 //
2629 // For Objective-C, we let A, B, and C also be Objective-C
2630 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002631
2632 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002633 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002634 SCS2.Second == ICK_Pointer_Conversion &&
2635 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2636 FromType1->isPointerType() && FromType2->isPointerType() &&
2637 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002638 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002639 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002640 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002641 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002642 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002643 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002644 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002645 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002646
John McCall8b07ec22010-05-15 11:32:37 +00002647 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2648 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2649 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2650 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002651
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002652 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002653 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002654 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002655 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002656 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002657 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002658
2659 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002660 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002661 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002662 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002663 return ImplicitConversionSequence::Worse;
2664 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002665 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002666
2667 // -- conversion of B* to A* is better than conversion of C* to A*,
2668 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002669 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002670 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002671 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002672 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002673
Douglas Gregor237f96c2008-11-26 23:31:11 +00002674 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002675 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002676 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002677 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002678 return ImplicitConversionSequence::Worse;
2679 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002680 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002681 }
2682
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002683 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002684 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2685 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2686 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2687 const MemberPointerType * FromMemPointer1 =
2688 FromType1->getAs<MemberPointerType>();
2689 const MemberPointerType * ToMemPointer1 =
2690 ToType1->getAs<MemberPointerType>();
2691 const MemberPointerType * FromMemPointer2 =
2692 FromType2->getAs<MemberPointerType>();
2693 const MemberPointerType * ToMemPointer2 =
2694 ToType2->getAs<MemberPointerType>();
2695 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2696 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2697 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2698 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2699 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2700 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2701 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2702 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002703 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002704 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002705 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002706 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002707 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002708 return ImplicitConversionSequence::Better;
2709 }
2710 // conversion of B::* to C::* is better than conversion of A::* to C::*
2711 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002712 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002713 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002714 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002715 return ImplicitConversionSequence::Worse;
2716 }
2717 }
2718
Douglas Gregor5ab11652010-04-17 22:01:05 +00002719 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002720 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002721 // -- binding of an expression of type C to a reference of type
2722 // B& is better than binding an expression of type C to a
2723 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002724 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2725 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2726 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002727 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002728 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002729 return ImplicitConversionSequence::Worse;
2730 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002731
Douglas Gregor2fe98832008-11-03 19:09:14 +00002732 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002733 // -- binding of an expression of type B to a reference of type
2734 // A& is better than binding an expression of type C to a
2735 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002736 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2737 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2738 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002739 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002740 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002741 return ImplicitConversionSequence::Worse;
2742 }
2743 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002744
Douglas Gregor5c407d92008-10-23 00:40:37 +00002745 return ImplicitConversionSequence::Indistinguishable;
2746}
2747
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002748/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2749/// determine whether they are reference-related,
2750/// reference-compatible, reference-compatible with added
2751/// qualification, or incompatible, for use in C++ initialization by
2752/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2753/// type, and the first type (T1) is the pointee type of the reference
2754/// type being initialized.
2755Sema::ReferenceCompareResult
2756Sema::CompareReferenceRelationship(SourceLocation Loc,
2757 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002758 bool &DerivedToBase,
2759 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002760 assert(!OrigT1->isReferenceType() &&
2761 "T1 must be the pointee type of the reference type");
2762 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2763
2764 QualType T1 = Context.getCanonicalType(OrigT1);
2765 QualType T2 = Context.getCanonicalType(OrigT2);
2766 Qualifiers T1Quals, T2Quals;
2767 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2768 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2769
2770 // C++ [dcl.init.ref]p4:
2771 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2772 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2773 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002774 DerivedToBase = false;
2775 ObjCConversion = false;
2776 if (UnqualT1 == UnqualT2) {
2777 // Nothing to do.
2778 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002779 IsDerivedFrom(UnqualT2, UnqualT1))
2780 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002781 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2782 UnqualT2->isObjCObjectOrInterfaceType() &&
2783 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2784 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002785 else
2786 return Ref_Incompatible;
2787
2788 // At this point, we know that T1 and T2 are reference-related (at
2789 // least).
2790
2791 // If the type is an array type, promote the element qualifiers to the type
2792 // for comparison.
2793 if (isa<ArrayType>(T1) && T1Quals)
2794 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2795 if (isa<ArrayType>(T2) && T2Quals)
2796 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2797
2798 // C++ [dcl.init.ref]p4:
2799 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2800 // reference-related to T2 and cv1 is the same cv-qualification
2801 // as, or greater cv-qualification than, cv2. For purposes of
2802 // overload resolution, cases for which cv1 is greater
2803 // cv-qualification than cv2 are identified as
2804 // reference-compatible with added qualification (see 13.3.3.2).
2805 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2806 return Ref_Compatible;
2807 else if (T1.isMoreQualifiedThan(T2))
2808 return Ref_Compatible_With_Added_Qualification;
2809 else
2810 return Ref_Related;
2811}
2812
Douglas Gregor836a7e82010-08-11 02:15:33 +00002813/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002814/// with DeclType. Return true if something definite is found.
2815static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002816FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2817 QualType DeclType, SourceLocation DeclLoc,
2818 Expr *Init, QualType T2, bool AllowRvalues,
2819 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002820 assert(T2->isRecordType() && "Can only find conversions of record types.");
2821 CXXRecordDecl *T2RecordDecl
2822 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2823
2824 OverloadCandidateSet CandidateSet(DeclLoc);
2825 const UnresolvedSetImpl *Conversions
2826 = T2RecordDecl->getVisibleConversionFunctions();
2827 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2828 E = Conversions->end(); I != E; ++I) {
2829 NamedDecl *D = *I;
2830 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2831 if (isa<UsingShadowDecl>(D))
2832 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2833
2834 FunctionTemplateDecl *ConvTemplate
2835 = dyn_cast<FunctionTemplateDecl>(D);
2836 CXXConversionDecl *Conv;
2837 if (ConvTemplate)
2838 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2839 else
2840 Conv = cast<CXXConversionDecl>(D);
2841
Douglas Gregor836a7e82010-08-11 02:15:33 +00002842 // If this is an explicit conversion, and we're not allowed to consider
2843 // explicit conversions, skip it.
2844 if (!AllowExplicit && Conv->isExplicit())
2845 continue;
2846
2847 if (AllowRvalues) {
2848 bool DerivedToBase = false;
2849 bool ObjCConversion = false;
2850 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00002851 S.CompareReferenceRelationship(
2852 DeclLoc,
2853 Conv->getConversionType().getNonReferenceType()
2854 .getUnqualifiedType(),
2855 DeclType.getNonReferenceType().getUnqualifiedType(),
2856 DerivedToBase, ObjCConversion) ==
2857 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00002858 continue;
2859 } else {
2860 // If the conversion function doesn't return a reference type,
2861 // it can't be considered for this conversion. An rvalue reference
2862 // is only acceptable if its referencee is a function type.
2863
2864 const ReferenceType *RefType =
2865 Conv->getConversionType()->getAs<ReferenceType>();
2866 if (!RefType ||
2867 (!RefType->isLValueReferenceType() &&
2868 !RefType->getPointeeType()->isFunctionType()))
2869 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002870 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002871
2872 if (ConvTemplate)
2873 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002874 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00002875 else
2876 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002877 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002878 }
2879
2880 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002881 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002882 case OR_Success:
2883 // C++ [over.ics.ref]p1:
2884 //
2885 // [...] If the parameter binds directly to the result of
2886 // applying a conversion function to the argument
2887 // expression, the implicit conversion sequence is a
2888 // user-defined conversion sequence (13.3.3.1.2), with the
2889 // second standard conversion sequence either an identity
2890 // conversion or, if the conversion function returns an
2891 // entity of a type that is a derived class of the parameter
2892 // type, a derived-to-base Conversion.
2893 if (!Best->FinalConversion.DirectBinding)
2894 return false;
2895
2896 ICS.setUserDefined();
2897 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2898 ICS.UserDefined.After = Best->FinalConversion;
2899 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002900 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00002901 ICS.UserDefined.EllipsisConversion = false;
2902 assert(ICS.UserDefined.After.ReferenceBinding &&
2903 ICS.UserDefined.After.DirectBinding &&
2904 "Expected a direct reference binding!");
2905 return true;
2906
2907 case OR_Ambiguous:
2908 ICS.setAmbiguous();
2909 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2910 Cand != CandidateSet.end(); ++Cand)
2911 if (Cand->Viable)
2912 ICS.Ambiguous.addConversion(Cand->Function);
2913 return true;
2914
2915 case OR_No_Viable_Function:
2916 case OR_Deleted:
2917 // There was no suitable conversion, or we found a deleted
2918 // conversion; continue with other checks.
2919 return false;
2920 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002921
2922 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002923}
2924
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002925/// \brief Compute an implicit conversion sequence for reference
2926/// initialization.
2927static ImplicitConversionSequence
2928TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2929 SourceLocation DeclLoc,
2930 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002931 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002932 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2933
2934 // Most paths end in a failed conversion.
2935 ImplicitConversionSequence ICS;
2936 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2937
2938 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2939 QualType T2 = Init->getType();
2940
2941 // If the initializer is the address of an overloaded function, try
2942 // to resolve the overloaded function. If all goes well, T2 is the
2943 // type of the resulting function.
2944 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2945 DeclAccessPair Found;
2946 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2947 false, Found))
2948 T2 = Fn->getType();
2949 }
2950
2951 // Compute some basic properties of the types and the initializer.
2952 bool isRValRef = DeclType->isRValueReferenceType();
2953 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002954 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002955 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002956 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002957 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2958 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002959
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002960
Sebastian Redld92badf2010-06-30 18:13:39 +00002961 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002962 // A reference to type "cv1 T1" is initialized by an expression
2963 // of type "cv2 T2" as follows:
2964
Sebastian Redld92badf2010-06-30 18:13:39 +00002965 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00002966 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002967 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2968 // reference-compatible with "cv2 T2," or
2969 //
2970 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2971 if (InitCategory.isLValue() &&
2972 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002973 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002974 // When a parameter of reference type binds directly (8.5.3)
2975 // to an argument expression, the implicit conversion sequence
2976 // is the identity conversion, unless the argument expression
2977 // has a type that is a derived class of the parameter type,
2978 // in which case the implicit conversion sequence is a
2979 // derived-to-base Conversion (13.3.3.1).
2980 ICS.setStandard();
2981 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002982 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2983 : ObjCConversion? ICK_Compatible_Conversion
2984 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002985 ICS.Standard.Third = ICK_Identity;
2986 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2987 ICS.Standard.setToType(0, T2);
2988 ICS.Standard.setToType(1, T1);
2989 ICS.Standard.setToType(2, T1);
2990 ICS.Standard.ReferenceBinding = true;
2991 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00002992 ICS.Standard.IsLvalueReference = !isRValRef;
2993 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
2994 ICS.Standard.BindsToRvalue = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002995 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002996
Sebastian Redld92badf2010-06-30 18:13:39 +00002997 // Nothing more to do: the inaccessibility/ambiguity check for
2998 // derived-to-base conversions is suppressed when we're
2999 // computing the implicit conversion sequence (C++
3000 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003001 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003002 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003003
Sebastian Redld92badf2010-06-30 18:13:39 +00003004 // -- has a class type (i.e., T2 is a class type), where T1 is
3005 // not reference-related to T2, and can be implicitly
3006 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3007 // is reference-compatible with "cv3 T3" 92) (this
3008 // conversion is selected by enumerating the applicable
3009 // conversion functions (13.3.1.6) and choosing the best
3010 // one through overload resolution (13.3)),
3011 if (!SuppressUserConversions && T2->isRecordType() &&
3012 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3013 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003014 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3015 Init, T2, /*AllowRvalues=*/false,
3016 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003017 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003018 }
3019 }
3020
Sebastian Redld92badf2010-06-30 18:13:39 +00003021 // -- Otherwise, the reference shall be an lvalue reference to a
3022 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003023 // shall be an rvalue reference.
Douglas Gregor870f3742010-04-18 09:22:00 +00003024 //
3025 // We actually handle one oddity of C++ [over.ics.ref] at this
3026 // point, which is that, due to p2 (which short-circuits reference
3027 // binding by only attempting a simple conversion for non-direct
3028 // bindings) and p3's strange wording, we allow a const volatile
3029 // reference to bind to an rvalue. Hence the check for the presence
3030 // of "const" rather than checking for "const" being the only
3031 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003032 // This is also the point where rvalue references and lvalue inits no longer
3033 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003034 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003035 return ICS;
3036
Douglas Gregorf143cd52011-01-24 16:14:37 +00003037 // -- If the initializer expression
3038 //
3039 // -- is an xvalue, class prvalue, array prvalue or function
3040 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3041 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3042 (InitCategory.isXValue() ||
3043 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3044 (InitCategory.isLValue() && T2->isFunctionType()))) {
3045 ICS.setStandard();
3046 ICS.Standard.First = ICK_Identity;
3047 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3048 : ObjCConversion? ICK_Compatible_Conversion
3049 : ICK_Identity;
3050 ICS.Standard.Third = ICK_Identity;
3051 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3052 ICS.Standard.setToType(0, T2);
3053 ICS.Standard.setToType(1, T1);
3054 ICS.Standard.setToType(2, T1);
3055 ICS.Standard.ReferenceBinding = true;
3056 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3057 // binding unless we're binding to a class prvalue.
3058 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3059 // allow the use of rvalue references in C++98/03 for the benefit of
3060 // standard library implementors; therefore, we need the xvalue check here.
3061 ICS.Standard.DirectBinding =
3062 S.getLangOptions().CPlusPlus0x ||
3063 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003064 ICS.Standard.IsLvalueReference = !isRValRef;
3065 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3066 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003067 ICS.Standard.CopyConstructor = 0;
3068 return ICS;
3069 }
3070
3071 // -- has a class type (i.e., T2 is a class type), where T1 is not
3072 // reference-related to T2, and can be implicitly converted to
3073 // an xvalue, class prvalue, or function lvalue of type
3074 // "cv3 T3", where "cv1 T1" is reference-compatible with
3075 // "cv3 T3",
3076 //
3077 // then the reference is bound to the value of the initializer
3078 // expression in the first case and to the result of the conversion
3079 // in the second case (or, in either case, to an appropriate base
3080 // class subobject).
3081 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3082 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3083 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3084 Init, T2, /*AllowRvalues=*/true,
3085 AllowExplicit)) {
3086 // In the second case, if the reference is an rvalue reference
3087 // and the second standard conversion sequence of the
3088 // user-defined conversion sequence includes an lvalue-to-rvalue
3089 // conversion, the program is ill-formed.
3090 if (ICS.isUserDefined() && isRValRef &&
3091 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3092 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3093
Douglas Gregor95273c32011-01-21 16:36:05 +00003094 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003095 }
Douglas Gregor95273c32011-01-21 16:36:05 +00003096
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003097 // -- Otherwise, a temporary of type "cv1 T1" is created and
3098 // initialized from the initializer expression using the
3099 // rules for a non-reference copy initialization (8.5). The
3100 // reference is then bound to the temporary. If T1 is
3101 // reference-related to T2, cv1 must be the same
3102 // cv-qualification as, or greater cv-qualification than,
3103 // cv2; otherwise, the program is ill-formed.
3104 if (RefRelationship == Sema::Ref_Related) {
3105 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3106 // we would be reference-compatible or reference-compatible with
3107 // added qualification. But that wasn't the case, so the reference
3108 // initialization fails.
3109 return ICS;
3110 }
3111
3112 // If at least one of the types is a class type, the types are not
3113 // related, and we aren't allowed any user conversions, the
3114 // reference binding fails. This case is important for breaking
3115 // recursion, since TryImplicitConversion below will attempt to
3116 // create a temporary through the use of a copy constructor.
3117 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3118 (T1->isRecordType() || T2->isRecordType()))
3119 return ICS;
3120
Douglas Gregorcba72b12011-01-21 05:18:22 +00003121 // If T1 is reference-related to T2 and the reference is an rvalue
3122 // reference, the initializer expression shall not be an lvalue.
3123 if (RefRelationship >= Sema::Ref_Related &&
3124 isRValRef && Init->Classify(S.Context).isLValue())
3125 return ICS;
3126
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003127 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003128 // When a parameter of reference type is not bound directly to
3129 // an argument expression, the conversion sequence is the one
3130 // required to convert the argument expression to the
3131 // underlying type of the reference according to
3132 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3133 // to copy-initializing a temporary of the underlying type with
3134 // the argument expression. Any difference in top-level
3135 // cv-qualification is subsumed by the initialization itself
3136 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003137 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3138 /*AllowExplicit=*/false,
3139 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003140
3141 // Of course, that's still a reference binding.
3142 if (ICS.isStandard()) {
3143 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003144 ICS.Standard.IsLvalueReference = !isRValRef;
3145 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3146 ICS.Standard.BindsToRvalue = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003147 } else if (ICS.isUserDefined()) {
3148 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003149 ICS.Standard.IsLvalueReference = !isRValRef;
3150 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3151 ICS.Standard.BindsToRvalue = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003152 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003153
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003154 return ICS;
3155}
3156
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003157/// TryCopyInitialization - Try to copy-initialize a value of type
3158/// ToType from the expression From. Return the implicit conversion
3159/// sequence required to pass this argument, which may be a bad
3160/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003161/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003162/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003163static ImplicitConversionSequence
3164TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003165 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003166 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003167 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003168 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003169 /*FIXME:*/From->getLocStart(),
3170 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003171 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003172
John McCall5c32be02010-08-24 20:38:10 +00003173 return TryImplicitConversion(S, From, ToType,
3174 SuppressUserConversions,
3175 /*AllowExplicit=*/false,
3176 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003177}
3178
Douglas Gregor436424c2008-11-18 23:14:02 +00003179/// TryObjectArgumentInitialization - Try to initialize the object
3180/// parameter of the given member function (@c Method) from the
3181/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003182static ImplicitConversionSequence
3183TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3184 CXXMethodDecl *Method,
3185 CXXRecordDecl *ActingContext) {
3186 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003187 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3188 // const volatile object.
3189 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3190 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003191 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003192
3193 // Set up the conversion sequence as a "bad" conversion, to allow us
3194 // to exit early.
3195 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003196
3197 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003198 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003199 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003200 FromType = PT->getPointeeType();
3201
3202 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003203
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003204 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003205 // where X is the class of which the function is a member
3206 // (C++ [over.match.funcs]p4). However, when finding an implicit
3207 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003208 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003209 // (C++ [over.match.funcs]p5). We perform a simplified version of
3210 // reference binding here, that allows class rvalues to bind to
3211 // non-constant references.
3212
3213 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3214 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003215 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003216 if (ImplicitParamType.getCVRQualifiers()
3217 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003218 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003219 ICS.setBad(BadConversionSequence::bad_qualifiers,
3220 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003221 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003222 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003223
3224 // Check that we have either the same type or a derived type. It
3225 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003226 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003227 ImplicitConversionKind SecondKind;
3228 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3229 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003230 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003231 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003232 else {
John McCall65eb8792010-02-25 01:37:24 +00003233 ICS.setBad(BadConversionSequence::unrelated_class,
3234 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003235 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003236 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003237
3238 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003239 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003240 ICS.Standard.setAsIdentityConversion();
3241 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003242 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003243 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003244 ICS.Standard.ReferenceBinding = true;
3245 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003246
3247 // FIXME: Rvalue references.
3248 ICS.Standard.IsLvalueReference = true;
3249 ICS.Standard.BindsToFunctionLvalue = false;
3250 ICS.Standard.BindsToRvalue = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003251 return ICS;
3252}
3253
3254/// PerformObjectArgumentInitialization - Perform initialization of
3255/// the implicit object parameter for the given Method with the given
3256/// expression.
3257bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003258Sema::PerformObjectArgumentInitialization(Expr *&From,
3259 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003260 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003261 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003262 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003263 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003264 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003265
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003266 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003267 FromRecordType = PT->getPointeeType();
3268 DestType = Method->getThisType(Context);
3269 } else {
3270 FromRecordType = From->getType();
3271 DestType = ImplicitParamRecordType;
3272 }
3273
John McCall6e9f8f62009-12-03 04:06:58 +00003274 // Note that we always use the true parent context when performing
3275 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003276 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003277 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003278 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003279 if (ICS.isBad()) {
3280 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3281 Qualifiers FromQs = FromRecordType.getQualifiers();
3282 Qualifiers ToQs = DestType.getQualifiers();
3283 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3284 if (CVR) {
3285 Diag(From->getSourceRange().getBegin(),
3286 diag::err_member_function_call_bad_cvr)
3287 << Method->getDeclName() << FromRecordType << (CVR - 1)
3288 << From->getSourceRange();
3289 Diag(Method->getLocation(), diag::note_previous_decl)
3290 << Method->getDeclName();
3291 return true;
3292 }
3293 }
3294
Douglas Gregor436424c2008-11-18 23:14:02 +00003295 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003296 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003297 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003298 }
Mike Stump11289f42009-09-09 15:08:12 +00003299
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003300 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003301 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003302
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003303 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003304 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003305 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003306 return false;
3307}
3308
Douglas Gregor5fb53972009-01-14 15:45:31 +00003309/// TryContextuallyConvertToBool - Attempt to contextually convert the
3310/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003311static ImplicitConversionSequence
3312TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003313 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003314 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003315 // FIXME: Are these flags correct?
3316 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003317 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003318 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003319}
3320
3321/// PerformContextuallyConvertToBool - Perform a contextual conversion
3322/// of the expression From to bool (C++0x [conv]p3).
3323bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003324 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003325 if (!ICS.isBad())
3326 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003327
Fariborz Jahanian76197412009-11-18 18:26:29 +00003328 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003329 return Diag(From->getSourceRange().getBegin(),
3330 diag::err_typecheck_bool_condition)
3331 << From->getType() << From->getSourceRange();
3332 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003333}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003334
3335/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3336/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003337static ImplicitConversionSequence
3338TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3339 QualType Ty = S.Context.getObjCIdType();
3340 return TryImplicitConversion(S, From, Ty,
3341 // FIXME: Are these flags correct?
3342 /*SuppressUserConversions=*/false,
3343 /*AllowExplicit=*/true,
3344 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003345}
John McCall5c32be02010-08-24 20:38:10 +00003346
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003347/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3348/// of the expression From to 'id'.
3349bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003350 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003351 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003352 if (!ICS.isBad())
3353 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3354 return true;
3355}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003356
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003357/// \brief Attempt to convert the given expression to an integral or
3358/// enumeration type.
3359///
3360/// This routine will attempt to convert an expression of class type to an
3361/// integral or enumeration type, if that class type only has a single
3362/// conversion to an integral or enumeration type.
3363///
Douglas Gregor4799d032010-06-30 00:20:43 +00003364/// \param Loc The source location of the construct that requires the
3365/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003366///
Douglas Gregor4799d032010-06-30 00:20:43 +00003367/// \param FromE The expression we're converting from.
3368///
3369/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3370/// have integral or enumeration type.
3371///
3372/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3373/// incomplete class type.
3374///
3375/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3376/// explicit conversion function (because no implicit conversion functions
3377/// were available). This is a recovery mode.
3378///
3379/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3380/// showing which conversion was picked.
3381///
3382/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3383/// conversion function that could convert to integral or enumeration type.
3384///
3385/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3386/// usable conversion function.
3387///
3388/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3389/// function, which may be an extension in this case.
3390///
3391/// \returns The expression, converted to an integral or enumeration type if
3392/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003393ExprResult
John McCallb268a282010-08-23 23:25:46 +00003394Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003395 const PartialDiagnostic &NotIntDiag,
3396 const PartialDiagnostic &IncompleteDiag,
3397 const PartialDiagnostic &ExplicitConvDiag,
3398 const PartialDiagnostic &ExplicitConvNote,
3399 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003400 const PartialDiagnostic &AmbigNote,
3401 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003402 // We can't perform any more checking for type-dependent expressions.
3403 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003404 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003405
3406 // If the expression already has integral or enumeration type, we're golden.
3407 QualType T = From->getType();
3408 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003409 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003410
3411 // FIXME: Check for missing '()' if T is a function type?
3412
3413 // If we don't have a class type in C++, there's no way we can get an
3414 // expression of integral or enumeration type.
3415 const RecordType *RecordTy = T->getAs<RecordType>();
3416 if (!RecordTy || !getLangOptions().CPlusPlus) {
3417 Diag(Loc, NotIntDiag)
3418 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003419 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003420 }
3421
3422 // We must have a complete class type.
3423 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003424 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003425
3426 // Look for a conversion to an integral or enumeration type.
3427 UnresolvedSet<4> ViableConversions;
3428 UnresolvedSet<4> ExplicitConversions;
3429 const UnresolvedSetImpl *Conversions
3430 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3431
3432 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3433 E = Conversions->end();
3434 I != E;
3435 ++I) {
3436 if (CXXConversionDecl *Conversion
3437 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3438 if (Conversion->getConversionType().getNonReferenceType()
3439 ->isIntegralOrEnumerationType()) {
3440 if (Conversion->isExplicit())
3441 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3442 else
3443 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3444 }
3445 }
3446
3447 switch (ViableConversions.size()) {
3448 case 0:
3449 if (ExplicitConversions.size() == 1) {
3450 DeclAccessPair Found = ExplicitConversions[0];
3451 CXXConversionDecl *Conversion
3452 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3453
3454 // The user probably meant to invoke the given explicit
3455 // conversion; use it.
3456 QualType ConvTy
3457 = Conversion->getConversionType().getNonReferenceType();
3458 std::string TypeStr;
3459 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3460
3461 Diag(Loc, ExplicitConvDiag)
3462 << T << ConvTy
3463 << FixItHint::CreateInsertion(From->getLocStart(),
3464 "static_cast<" + TypeStr + ">(")
3465 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3466 ")");
3467 Diag(Conversion->getLocation(), ExplicitConvNote)
3468 << ConvTy->isEnumeralType() << ConvTy;
3469
3470 // If we aren't in a SFINAE context, build a call to the
3471 // explicit conversion function.
3472 if (isSFINAEContext())
3473 return ExprError();
3474
3475 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003476 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3477 if (Result.isInvalid())
3478 return ExprError();
3479
3480 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003481 }
3482
3483 // We'll complain below about a non-integral condition type.
3484 break;
3485
3486 case 1: {
3487 // Apply this conversion.
3488 DeclAccessPair Found = ViableConversions[0];
3489 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003490
3491 CXXConversionDecl *Conversion
3492 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3493 QualType ConvTy
3494 = Conversion->getConversionType().getNonReferenceType();
3495 if (ConvDiag.getDiagID()) {
3496 if (isSFINAEContext())
3497 return ExprError();
3498
3499 Diag(Loc, ConvDiag)
3500 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3501 }
3502
Douglas Gregor668443e2011-01-20 00:18:04 +00003503 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003504 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003505 if (Result.isInvalid())
3506 return ExprError();
3507
3508 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003509 break;
3510 }
3511
3512 default:
3513 Diag(Loc, AmbigDiag)
3514 << T << From->getSourceRange();
3515 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3516 CXXConversionDecl *Conv
3517 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3518 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3519 Diag(Conv->getLocation(), AmbigNote)
3520 << ConvTy->isEnumeralType() << ConvTy;
3521 }
John McCallb268a282010-08-23 23:25:46 +00003522 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003523 }
3524
Douglas Gregor5823da32010-06-29 23:25:20 +00003525 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003526 Diag(Loc, NotIntDiag)
3527 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003528
John McCallb268a282010-08-23 23:25:46 +00003529 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003530}
3531
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003532/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003533/// candidate functions, using the given function call arguments. If
3534/// @p SuppressUserConversions, then don't allow user-defined
3535/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003536///
3537/// \para PartialOverloading true if we are performing "partial" overloading
3538/// based on an incomplete set of function arguments. This feature is used by
3539/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003540void
3541Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003542 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003543 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003544 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003545 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003546 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003547 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003548 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003549 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003550 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003551 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003552
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003553 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003554 if (!isa<CXXConstructorDecl>(Method)) {
3555 // If we get here, it's because we're calling a member function
3556 // that is named without a member access expression (e.g.,
3557 // "this->f") that was either written explicitly or created
3558 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003559 // function, e.g., X::f(). We use an empty type for the implied
3560 // object argument (C++ [over.call.func]p3), and the acting context
3561 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003562 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003563 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003564 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003565 return;
3566 }
3567 // We treat a constructor like a non-member function, since its object
3568 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003569 }
3570
Douglas Gregorff7028a2009-11-13 23:59:09 +00003571 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003572 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003573
Douglas Gregor27381f32009-11-23 12:27:39 +00003574 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003575 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003576
Douglas Gregorffe14e32009-11-14 01:20:54 +00003577 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3578 // C++ [class.copy]p3:
3579 // A member function template is never instantiated to perform the copy
3580 // of a class object to an object of its class type.
3581 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3582 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003583 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003584 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3585 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003586 return;
3587 }
3588
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003589 // Add this candidate
3590 CandidateSet.push_back(OverloadCandidate());
3591 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003592 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003593 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003594 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003595 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003596 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003597 Candidate.ExplicitCallArguments = NumArgs;
3598
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003599 unsigned NumArgsInProto = Proto->getNumArgs();
3600
3601 // (C++ 13.3.2p2): A candidate function having fewer than m
3602 // parameters is viable only if it has an ellipsis in its parameter
3603 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003604 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3605 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003606 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003607 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003608 return;
3609 }
3610
3611 // (C++ 13.3.2p2): A candidate function having more than m parameters
3612 // is viable only if the (m+1)st parameter has a default argument
3613 // (8.3.6). For the purposes of overload resolution, the
3614 // parameter list is truncated on the right, so that there are
3615 // exactly m parameters.
3616 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003617 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003618 // Not enough arguments.
3619 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003620 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003621 return;
3622 }
3623
3624 // Determine the implicit conversion sequences for each of the
3625 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003626 Candidate.Conversions.resize(NumArgs);
3627 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3628 if (ArgIdx < NumArgsInProto) {
3629 // (C++ 13.3.2p3): for F to be a viable function, there shall
3630 // exist for each argument an implicit conversion sequence
3631 // (13.3.3.1) that converts that argument to the corresponding
3632 // parameter of F.
3633 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003634 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003635 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003636 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003637 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003638 if (Candidate.Conversions[ArgIdx].isBad()) {
3639 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003640 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003641 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003642 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003643 } else {
3644 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3645 // argument for which there is no corresponding parameter is
3646 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003647 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003648 }
3649 }
3650}
3651
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003652/// \brief Add all of the function declarations in the given function set to
3653/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003654void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003655 Expr **Args, unsigned NumArgs,
3656 OverloadCandidateSet& CandidateSet,
3657 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003658 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003659 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3660 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003661 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003662 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003663 cast<CXXMethodDecl>(FD)->getParent(),
3664 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003665 CandidateSet, SuppressUserConversions);
3666 else
John McCalla0296f72010-03-19 07:35:19 +00003667 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003668 SuppressUserConversions);
3669 } else {
John McCalla0296f72010-03-19 07:35:19 +00003670 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003671 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3672 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003673 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003674 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003675 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003676 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003677 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003678 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003679 else
John McCalla0296f72010-03-19 07:35:19 +00003680 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003681 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003682 Args, NumArgs, CandidateSet,
3683 SuppressUserConversions);
3684 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003685 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003686}
3687
John McCallf0f1cf02009-11-17 07:50:12 +00003688/// AddMethodCandidate - Adds a named decl (which is some kind of
3689/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003690void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003691 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003692 Expr **Args, unsigned NumArgs,
3693 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003694 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003695 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003696 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003697
3698 if (isa<UsingShadowDecl>(Decl))
3699 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3700
3701 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3702 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3703 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003704 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3705 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003706 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003707 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003708 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003709 } else {
John McCalla0296f72010-03-19 07:35:19 +00003710 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003711 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003712 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003713 }
3714}
3715
Douglas Gregor436424c2008-11-18 23:14:02 +00003716/// AddMethodCandidate - Adds the given C++ member function to the set
3717/// of candidate functions, using the given function call arguments
3718/// and the object argument (@c Object). For example, in a call
3719/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3720/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3721/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003722/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003723void
John McCalla0296f72010-03-19 07:35:19 +00003724Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003725 CXXRecordDecl *ActingContext, QualType ObjectType,
3726 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003727 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003728 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003729 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003730 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003731 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003732 assert(!isa<CXXConstructorDecl>(Method) &&
3733 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003734
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003735 if (!CandidateSet.isNewCandidate(Method))
3736 return;
3737
Douglas Gregor27381f32009-11-23 12:27:39 +00003738 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003739 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003740
Douglas Gregor436424c2008-11-18 23:14:02 +00003741 // Add this candidate
3742 CandidateSet.push_back(OverloadCandidate());
3743 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003744 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003745 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003746 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003747 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003748 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00003749
3750 unsigned NumArgsInProto = Proto->getNumArgs();
3751
3752 // (C++ 13.3.2p2): A candidate function having fewer than m
3753 // parameters is viable only if it has an ellipsis in its parameter
3754 // list (8.3.5).
3755 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3756 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003757 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003758 return;
3759 }
3760
3761 // (C++ 13.3.2p2): A candidate function having more than m parameters
3762 // is viable only if the (m+1)st parameter has a default argument
3763 // (8.3.6). For the purposes of overload resolution, the
3764 // parameter list is truncated on the right, so that there are
3765 // exactly m parameters.
3766 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3767 if (NumArgs < MinRequiredArgs) {
3768 // Not enough arguments.
3769 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003770 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003771 return;
3772 }
3773
3774 Candidate.Viable = true;
3775 Candidate.Conversions.resize(NumArgs + 1);
3776
John McCall6e9f8f62009-12-03 04:06:58 +00003777 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003778 // The implicit object argument is ignored.
3779 Candidate.IgnoreObjectArgument = true;
3780 else {
3781 // Determine the implicit conversion sequence for the object
3782 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003783 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003784 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3785 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003786 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003787 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003788 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003789 return;
3790 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003791 }
3792
3793 // Determine the implicit conversion sequences for each of the
3794 // arguments.
3795 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3796 if (ArgIdx < NumArgsInProto) {
3797 // (C++ 13.3.2p3): for F to be a viable function, there shall
3798 // exist for each argument an implicit conversion sequence
3799 // (13.3.3.1) that converts that argument to the corresponding
3800 // parameter of F.
3801 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003802 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003803 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003804 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003805 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003806 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003807 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003808 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003809 break;
3810 }
3811 } else {
3812 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3813 // argument for which there is no corresponding parameter is
3814 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003815 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003816 }
3817 }
3818}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003819
Douglas Gregor97628d62009-08-21 00:16:32 +00003820/// \brief Add a C++ member function template as a candidate to the candidate
3821/// set, using template argument deduction to produce an appropriate member
3822/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003823void
Douglas Gregor97628d62009-08-21 00:16:32 +00003824Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003825 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003826 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003827 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003828 QualType ObjectType,
3829 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003830 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003831 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003832 if (!CandidateSet.isNewCandidate(MethodTmpl))
3833 return;
3834
Douglas Gregor97628d62009-08-21 00:16:32 +00003835 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003836 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003837 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003838 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003839 // candidate functions in the usual way.113) A given name can refer to one
3840 // or more function templates and also to a set of overloaded non-template
3841 // functions. In such a case, the candidate functions generated from each
3842 // function template are combined with the set of non-template candidate
3843 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003844 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003845 FunctionDecl *Specialization = 0;
3846 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003847 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003848 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003849 CandidateSet.push_back(OverloadCandidate());
3850 OverloadCandidate &Candidate = CandidateSet.back();
3851 Candidate.FoundDecl = FoundDecl;
3852 Candidate.Function = MethodTmpl->getTemplatedDecl();
3853 Candidate.Viable = false;
3854 Candidate.FailureKind = ovl_fail_bad_deduction;
3855 Candidate.IsSurrogate = false;
3856 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003857 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003858 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3859 Info);
3860 return;
3861 }
Mike Stump11289f42009-09-09 15:08:12 +00003862
Douglas Gregor97628d62009-08-21 00:16:32 +00003863 // Add the function template specialization produced by template argument
3864 // deduction as a candidate.
3865 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003866 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003867 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003868 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003869 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003870 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003871}
3872
Douglas Gregor05155d82009-08-21 23:19:43 +00003873/// \brief Add a C++ function template specialization as a candidate
3874/// in the candidate set, using template argument deduction to produce
3875/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003876void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003877Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003878 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003879 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003880 Expr **Args, unsigned NumArgs,
3881 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003882 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003883 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3884 return;
3885
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003886 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003887 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003888 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003889 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003890 // candidate functions in the usual way.113) A given name can refer to one
3891 // or more function templates and also to a set of overloaded non-template
3892 // functions. In such a case, the candidate functions generated from each
3893 // function template are combined with the set of non-template candidate
3894 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003895 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003896 FunctionDecl *Specialization = 0;
3897 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003898 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003899 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003900 CandidateSet.push_back(OverloadCandidate());
3901 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003902 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003903 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3904 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003905 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003906 Candidate.IsSurrogate = false;
3907 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003908 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003909 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3910 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003911 return;
3912 }
Mike Stump11289f42009-09-09 15:08:12 +00003913
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003914 // Add the function template specialization produced by template argument
3915 // deduction as a candidate.
3916 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003917 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003918 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003919}
Mike Stump11289f42009-09-09 15:08:12 +00003920
Douglas Gregora1f013e2008-11-07 22:36:19 +00003921/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003922/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003923/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003924/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003925/// (which may or may not be the same type as the type that the
3926/// conversion function produces).
3927void
3928Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003929 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003930 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003931 Expr *From, QualType ToType,
3932 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003933 assert(!Conversion->getDescribedFunctionTemplate() &&
3934 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003935 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003936 if (!CandidateSet.isNewCandidate(Conversion))
3937 return;
3938
Douglas Gregor27381f32009-11-23 12:27:39 +00003939 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003940 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003941
Douglas Gregora1f013e2008-11-07 22:36:19 +00003942 // Add this candidate
3943 CandidateSet.push_back(OverloadCandidate());
3944 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003945 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003946 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003947 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003948 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003949 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003950 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003951 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003952 Candidate.Viable = true;
3953 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00003954 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003955
Douglas Gregor6affc782010-08-19 15:37:02 +00003956 // C++ [over.match.funcs]p4:
3957 // For conversion functions, the function is considered to be a member of
3958 // the class of the implicit implied object argument for the purpose of
3959 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003960 //
3961 // Determine the implicit conversion sequence for the implicit
3962 // object parameter.
3963 QualType ImplicitParamType = From->getType();
3964 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3965 ImplicitParamType = FromPtrType->getPointeeType();
3966 CXXRecordDecl *ConversionContext
3967 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3968
3969 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003970 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003971 ConversionContext);
3972
John McCall0d1da222010-01-12 00:44:57 +00003973 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003974 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003975 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003976 return;
3977 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003978
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003979 // We won't go through a user-define type conversion function to convert a
3980 // derived to base as such conversions are given Conversion Rank. They only
3981 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3982 QualType FromCanon
3983 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3984 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3985 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3986 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003987 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003988 return;
3989 }
3990
Douglas Gregora1f013e2008-11-07 22:36:19 +00003991 // To determine what the conversion from the result of calling the
3992 // conversion function to the type we're eventually trying to
3993 // convert to (ToType), we need to synthesize a call to the
3994 // conversion function and attempt copy initialization from it. This
3995 // makes sure that we get the right semantics with respect to
3996 // lvalues/rvalues and the type. Fortunately, we can allocate this
3997 // call on the stack and we don't need its arguments to be
3998 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003999 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004000 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004001 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4002 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004003 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004004 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004005
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004006 QualType CallResultType
4007 = Conversion->getConversionType().getNonLValueExprType(Context);
4008 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4009 Candidate.Viable = false;
4010 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4011 return;
4012 }
4013
John McCall7decc9e2010-11-18 06:31:45 +00004014 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4015
Mike Stump11289f42009-09-09 15:08:12 +00004016 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004017 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4018 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004019 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004020 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004021 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004022 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004023 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004024 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004025
John McCall0d1da222010-01-12 00:44:57 +00004026 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004027 case ImplicitConversionSequence::StandardConversion:
4028 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004029
4030 // C++ [over.ics.user]p3:
4031 // If the user-defined conversion is specified by a specialization of a
4032 // conversion function template, the second standard conversion sequence
4033 // shall have exact match rank.
4034 if (Conversion->getPrimaryTemplate() &&
4035 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4036 Candidate.Viable = false;
4037 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4038 }
4039
Douglas Gregorcba72b12011-01-21 05:18:22 +00004040 // C++0x [dcl.init.ref]p5:
4041 // In the second case, if the reference is an rvalue reference and
4042 // the second standard conversion sequence of the user-defined
4043 // conversion sequence includes an lvalue-to-rvalue conversion, the
4044 // program is ill-formed.
4045 if (ToType->isRValueReferenceType() &&
4046 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4047 Candidate.Viable = false;
4048 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4049 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004050 break;
4051
4052 case ImplicitConversionSequence::BadConversion:
4053 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004054 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004055 break;
4056
4057 default:
Mike Stump11289f42009-09-09 15:08:12 +00004058 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004059 "Can only end up with a standard conversion sequence or failure");
4060 }
4061}
4062
Douglas Gregor05155d82009-08-21 23:19:43 +00004063/// \brief Adds a conversion function template specialization
4064/// candidate to the overload set, using template argument deduction
4065/// to deduce the template arguments of the conversion function
4066/// template from the type that we are converting to (C++
4067/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004068void
Douglas Gregor05155d82009-08-21 23:19:43 +00004069Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004070 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004071 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004072 Expr *From, QualType ToType,
4073 OverloadCandidateSet &CandidateSet) {
4074 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4075 "Only conversion function templates permitted here");
4076
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004077 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4078 return;
4079
John McCallbc077cf2010-02-08 23:07:23 +00004080 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004081 CXXConversionDecl *Specialization = 0;
4082 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004083 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004084 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004085 CandidateSet.push_back(OverloadCandidate());
4086 OverloadCandidate &Candidate = CandidateSet.back();
4087 Candidate.FoundDecl = FoundDecl;
4088 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4089 Candidate.Viable = false;
4090 Candidate.FailureKind = ovl_fail_bad_deduction;
4091 Candidate.IsSurrogate = false;
4092 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004093 Candidate.ExplicitCallArguments = 1;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004094 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4095 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004096 return;
4097 }
Mike Stump11289f42009-09-09 15:08:12 +00004098
Douglas Gregor05155d82009-08-21 23:19:43 +00004099 // Add the conversion function template specialization produced by
4100 // template argument deduction as a candidate.
4101 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004102 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004103 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004104}
4105
Douglas Gregorab7897a2008-11-19 22:57:39 +00004106/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4107/// converts the given @c Object to a function pointer via the
4108/// conversion function @c Conversion, and then attempts to call it
4109/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4110/// the type of function that we'll eventually be calling.
4111void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004112 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004113 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004114 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00004115 QualType ObjectType,
4116 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004117 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004118 if (!CandidateSet.isNewCandidate(Conversion))
4119 return;
4120
Douglas Gregor27381f32009-11-23 12:27:39 +00004121 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004122 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004123
Douglas Gregorab7897a2008-11-19 22:57:39 +00004124 CandidateSet.push_back(OverloadCandidate());
4125 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004126 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004127 Candidate.Function = 0;
4128 Candidate.Surrogate = Conversion;
4129 Candidate.Viable = true;
4130 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004131 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004132 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004133 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004134
4135 // Determine the implicit conversion sequence for the implicit
4136 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004137 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00004138 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4139 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004140 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004141 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004142 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004143 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004144 return;
4145 }
4146
4147 // The first conversion is actually a user-defined conversion whose
4148 // first conversion is ObjectInit's standard conversion (which is
4149 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004150 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004151 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004152 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004153 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004154 Candidate.Conversions[0].UserDefined.FoundConversionFunction
4155 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004156 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004157 = Candidate.Conversions[0].UserDefined.Before;
4158 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4159
Mike Stump11289f42009-09-09 15:08:12 +00004160 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004161 unsigned NumArgsInProto = Proto->getNumArgs();
4162
4163 // (C++ 13.3.2p2): A candidate function having fewer than m
4164 // parameters is viable only if it has an ellipsis in its parameter
4165 // list (8.3.5).
4166 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4167 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004168 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004169 return;
4170 }
4171
4172 // Function types don't have any default arguments, so just check if
4173 // we have enough arguments.
4174 if (NumArgs < NumArgsInProto) {
4175 // Not enough arguments.
4176 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004177 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004178 return;
4179 }
4180
4181 // Determine the implicit conversion sequences for each of the
4182 // arguments.
4183 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4184 if (ArgIdx < NumArgsInProto) {
4185 // (C++ 13.3.2p3): for F to be a viable function, there shall
4186 // exist for each argument an implicit conversion sequence
4187 // (13.3.3.1) that converts that argument to the corresponding
4188 // parameter of F.
4189 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004190 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004191 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004192 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004193 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004194 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004195 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004196 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004197 break;
4198 }
4199 } else {
4200 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4201 // argument for which there is no corresponding parameter is
4202 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004203 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004204 }
4205 }
4206}
4207
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004208/// \brief Add overload candidates for overloaded operators that are
4209/// member functions.
4210///
4211/// Add the overloaded operator candidates that are member functions
4212/// for the operator Op that was used in an operator expression such
4213/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4214/// CandidateSet will store the added overload candidates. (C++
4215/// [over.match.oper]).
4216void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4217 SourceLocation OpLoc,
4218 Expr **Args, unsigned NumArgs,
4219 OverloadCandidateSet& CandidateSet,
4220 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004221 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4222
4223 // C++ [over.match.oper]p3:
4224 // For a unary operator @ with an operand of a type whose
4225 // cv-unqualified version is T1, and for a binary operator @ with
4226 // a left operand of a type whose cv-unqualified version is T1 and
4227 // a right operand of a type whose cv-unqualified version is T2,
4228 // three sets of candidate functions, designated member
4229 // candidates, non-member candidates and built-in candidates, are
4230 // constructed as follows:
4231 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004232
4233 // -- If T1 is a class type, the set of member candidates is the
4234 // result of the qualified lookup of T1::operator@
4235 // (13.3.1.1.1); otherwise, the set of member candidates is
4236 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004237 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004238 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004239 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004240 return;
Mike Stump11289f42009-09-09 15:08:12 +00004241
John McCall27b18f82009-11-17 02:14:36 +00004242 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4243 LookupQualifiedName(Operators, T1Rec->getDecl());
4244 Operators.suppressDiagnostics();
4245
Mike Stump11289f42009-09-09 15:08:12 +00004246 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004247 OperEnd = Operators.end();
4248 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004249 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004250 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004251 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004252 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004253 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004254}
4255
Douglas Gregora11693b2008-11-12 17:17:38 +00004256/// AddBuiltinCandidate - Add a candidate for a built-in
4257/// operator. ResultTy and ParamTys are the result and parameter types
4258/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004259/// arguments being passed to the candidate. IsAssignmentOperator
4260/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004261/// operator. NumContextualBoolArguments is the number of arguments
4262/// (at the beginning of the argument list) that will be contextually
4263/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004264void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004265 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004266 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004267 bool IsAssignmentOperator,
4268 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004269 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004270 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004271
Douglas Gregora11693b2008-11-12 17:17:38 +00004272 // Add this candidate
4273 CandidateSet.push_back(OverloadCandidate());
4274 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004275 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004276 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004277 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004278 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004279 Candidate.BuiltinTypes.ResultTy = ResultTy;
4280 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4281 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4282
4283 // Determine the implicit conversion sequences for each of the
4284 // arguments.
4285 Candidate.Viable = true;
4286 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004287 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004288 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004289 // C++ [over.match.oper]p4:
4290 // For the built-in assignment operators, conversions of the
4291 // left operand are restricted as follows:
4292 // -- no temporaries are introduced to hold the left operand, and
4293 // -- no user-defined conversions are applied to the left
4294 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004295 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004296 //
4297 // We block these conversions by turning off user-defined
4298 // conversions, since that is the only way that initialization of
4299 // a reference to a non-class type can occur from something that
4300 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004301 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004302 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004303 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004304 Candidate.Conversions[ArgIdx]
4305 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004306 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004307 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004308 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004309 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004310 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004311 }
John McCall0d1da222010-01-12 00:44:57 +00004312 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004313 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004314 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004315 break;
4316 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004317 }
4318}
4319
4320/// BuiltinCandidateTypeSet - A set of types that will be used for the
4321/// candidate operator functions for built-in operators (C++
4322/// [over.built]). The types are separated into pointer types and
4323/// enumeration types.
4324class BuiltinCandidateTypeSet {
4325 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004326 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004327
4328 /// PointerTypes - The set of pointer types that will be used in the
4329 /// built-in candidates.
4330 TypeSet PointerTypes;
4331
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004332 /// MemberPointerTypes - The set of member pointer types that will be
4333 /// used in the built-in candidates.
4334 TypeSet MemberPointerTypes;
4335
Douglas Gregora11693b2008-11-12 17:17:38 +00004336 /// EnumerationTypes - The set of enumeration types that will be
4337 /// used in the built-in candidates.
4338 TypeSet EnumerationTypes;
4339
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004340 /// \brief The set of vector types that will be used in the built-in
4341 /// candidates.
4342 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004343
4344 /// \brief A flag indicating non-record types are viable candidates
4345 bool HasNonRecordTypes;
4346
4347 /// \brief A flag indicating whether either arithmetic or enumeration types
4348 /// were present in the candidate set.
4349 bool HasArithmeticOrEnumeralTypes;
4350
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004351 /// Sema - The semantic analysis instance where we are building the
4352 /// candidate type set.
4353 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004354
Douglas Gregora11693b2008-11-12 17:17:38 +00004355 /// Context - The AST context in which we will build the type sets.
4356 ASTContext &Context;
4357
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004358 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4359 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004360 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004361
4362public:
4363 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004364 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004365
Mike Stump11289f42009-09-09 15:08:12 +00004366 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004367 : HasNonRecordTypes(false),
4368 HasArithmeticOrEnumeralTypes(false),
4369 SemaRef(SemaRef),
4370 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004371
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004372 void AddTypesConvertedFrom(QualType Ty,
4373 SourceLocation Loc,
4374 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004375 bool AllowExplicitConversions,
4376 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004377
4378 /// pointer_begin - First pointer type found;
4379 iterator pointer_begin() { return PointerTypes.begin(); }
4380
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004381 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004382 iterator pointer_end() { return PointerTypes.end(); }
4383
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004384 /// member_pointer_begin - First member pointer type found;
4385 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4386
4387 /// member_pointer_end - Past the last member pointer type found;
4388 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4389
Douglas Gregora11693b2008-11-12 17:17:38 +00004390 /// enumeration_begin - First enumeration type found;
4391 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4392
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004393 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004394 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004395
4396 iterator vector_begin() { return VectorTypes.begin(); }
4397 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004398
4399 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4400 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004401};
4402
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004403/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004404/// the set of pointer types along with any more-qualified variants of
4405/// that type. For example, if @p Ty is "int const *", this routine
4406/// will add "int const *", "int const volatile *", "int const
4407/// restrict *", and "int const volatile restrict *" to the set of
4408/// pointer types. Returns true if the add of @p Ty itself succeeded,
4409/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004410///
4411/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004412bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004413BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4414 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004415
Douglas Gregora11693b2008-11-12 17:17:38 +00004416 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004417 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004418 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004419
4420 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004421 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004422 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004423 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004424 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004425 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004426 buildObjCPtr = true;
4427 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004428 else
4429 assert(false && "type was not a pointer type!");
4430 }
4431 else
4432 PointeeTy = PointerTy->getPointeeType();
4433
Sebastian Redl4990a632009-11-18 20:39:26 +00004434 // Don't add qualified variants of arrays. For one, they're not allowed
4435 // (the qualifier would sink to the element type), and for another, the
4436 // only overload situation where it matters is subscript or pointer +- int,
4437 // and those shouldn't have qualifier variants anyway.
4438 if (PointeeTy->isArrayType())
4439 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004440 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004441 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004442 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004443 bool hasVolatile = VisibleQuals.hasVolatile();
4444 bool hasRestrict = VisibleQuals.hasRestrict();
4445
John McCall8ccfcb52009-09-24 19:53:00 +00004446 // Iterate through all strict supersets of BaseCVR.
4447 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4448 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004449 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4450 // in the types.
4451 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4452 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004453 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004454 if (!buildObjCPtr)
4455 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4456 else
4457 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004458 }
4459
4460 return true;
4461}
4462
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004463/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4464/// to the set of pointer types along with any more-qualified variants of
4465/// that type. For example, if @p Ty is "int const *", this routine
4466/// will add "int const *", "int const volatile *", "int const
4467/// restrict *", and "int const volatile restrict *" to the set of
4468/// pointer types. Returns true if the add of @p Ty itself succeeded,
4469/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004470///
4471/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004472bool
4473BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4474 QualType Ty) {
4475 // Insert this type.
4476 if (!MemberPointerTypes.insert(Ty))
4477 return false;
4478
John McCall8ccfcb52009-09-24 19:53:00 +00004479 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4480 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004481
John McCall8ccfcb52009-09-24 19:53:00 +00004482 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004483 // Don't add qualified variants of arrays. For one, they're not allowed
4484 // (the qualifier would sink to the element type), and for another, the
4485 // only overload situation where it matters is subscript or pointer +- int,
4486 // and those shouldn't have qualifier variants anyway.
4487 if (PointeeTy->isArrayType())
4488 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004489 const Type *ClassTy = PointerTy->getClass();
4490
4491 // Iterate through all strict supersets of the pointee type's CVR
4492 // qualifiers.
4493 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4494 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4495 if ((CVR | BaseCVR) != CVR) continue;
4496
4497 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004498 MemberPointerTypes.insert(
4499 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004500 }
4501
4502 return true;
4503}
4504
Douglas Gregora11693b2008-11-12 17:17:38 +00004505/// AddTypesConvertedFrom - Add each of the types to which the type @p
4506/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004507/// primarily interested in pointer types and enumeration types. We also
4508/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004509/// AllowUserConversions is true if we should look at the conversion
4510/// functions of a class type, and AllowExplicitConversions if we
4511/// should also include the explicit conversion functions of a class
4512/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004513void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004514BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004515 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004516 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004517 bool AllowExplicitConversions,
4518 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004519 // Only deal with canonical types.
4520 Ty = Context.getCanonicalType(Ty);
4521
4522 // Look through reference types; they aren't part of the type of an
4523 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004524 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004525 Ty = RefTy->getPointeeType();
4526
John McCall33ddac02011-01-19 10:06:00 +00004527 // If we're dealing with an array type, decay to the pointer.
4528 if (Ty->isArrayType())
4529 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4530
4531 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004532 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004533
Chandler Carruth00a38332010-12-13 01:44:01 +00004534 // Flag if we ever add a non-record type.
4535 const RecordType *TyRec = Ty->getAs<RecordType>();
4536 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4537
Chandler Carruth00a38332010-12-13 01:44:01 +00004538 // Flag if we encounter an arithmetic type.
4539 HasArithmeticOrEnumeralTypes =
4540 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4541
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004542 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4543 PointerTypes.insert(Ty);
4544 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004545 // Insert our type, and its more-qualified variants, into the set
4546 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004547 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004548 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004549 } else if (Ty->isMemberPointerType()) {
4550 // Member pointers are far easier, since the pointee can't be converted.
4551 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4552 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004553 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004554 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004555 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004556 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004557 // We treat vector types as arithmetic types in many contexts as an
4558 // extension.
4559 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004560 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004561 } else if (AllowUserConversions && TyRec) {
4562 // No conversion functions in incomplete types.
4563 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4564 return;
Mike Stump11289f42009-09-09 15:08:12 +00004565
Chandler Carruth00a38332010-12-13 01:44:01 +00004566 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4567 const UnresolvedSetImpl *Conversions
4568 = ClassDecl->getVisibleConversionFunctions();
4569 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4570 E = Conversions->end(); I != E; ++I) {
4571 NamedDecl *D = I.getDecl();
4572 if (isa<UsingShadowDecl>(D))
4573 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004574
Chandler Carruth00a38332010-12-13 01:44:01 +00004575 // Skip conversion function templates; they don't tell us anything
4576 // about which builtin types we can convert to.
4577 if (isa<FunctionTemplateDecl>(D))
4578 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004579
Chandler Carruth00a38332010-12-13 01:44:01 +00004580 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4581 if (AllowExplicitConversions || !Conv->isExplicit()) {
4582 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4583 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004584 }
4585 }
4586 }
4587}
4588
Douglas Gregor84605ae2009-08-24 13:43:27 +00004589/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4590/// the volatile- and non-volatile-qualified assignment operators for the
4591/// given type to the candidate set.
4592static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4593 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004594 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004595 unsigned NumArgs,
4596 OverloadCandidateSet &CandidateSet) {
4597 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004598
Douglas Gregor84605ae2009-08-24 13:43:27 +00004599 // T& operator=(T&, T)
4600 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4601 ParamTypes[1] = T;
4602 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4603 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004604
Douglas Gregor84605ae2009-08-24 13:43:27 +00004605 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4606 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004607 ParamTypes[0]
4608 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004609 ParamTypes[1] = T;
4610 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004611 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004612 }
4613}
Mike Stump11289f42009-09-09 15:08:12 +00004614
Sebastian Redl1054fae2009-10-25 17:03:50 +00004615/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4616/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004617static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4618 Qualifiers VRQuals;
4619 const RecordType *TyRec;
4620 if (const MemberPointerType *RHSMPType =
4621 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004622 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004623 else
4624 TyRec = ArgExpr->getType()->getAs<RecordType>();
4625 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004626 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004627 VRQuals.addVolatile();
4628 VRQuals.addRestrict();
4629 return VRQuals;
4630 }
4631
4632 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004633 if (!ClassDecl->hasDefinition())
4634 return VRQuals;
4635
John McCallad371252010-01-20 00:46:10 +00004636 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004637 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004638
John McCallad371252010-01-20 00:46:10 +00004639 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004640 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004641 NamedDecl *D = I.getDecl();
4642 if (isa<UsingShadowDecl>(D))
4643 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4644 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004645 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4646 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4647 CanTy = ResTypeRef->getPointeeType();
4648 // Need to go down the pointer/mempointer chain and add qualifiers
4649 // as see them.
4650 bool done = false;
4651 while (!done) {
4652 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4653 CanTy = ResTypePtr->getPointeeType();
4654 else if (const MemberPointerType *ResTypeMPtr =
4655 CanTy->getAs<MemberPointerType>())
4656 CanTy = ResTypeMPtr->getPointeeType();
4657 else
4658 done = true;
4659 if (CanTy.isVolatileQualified())
4660 VRQuals.addVolatile();
4661 if (CanTy.isRestrictQualified())
4662 VRQuals.addRestrict();
4663 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4664 return VRQuals;
4665 }
4666 }
4667 }
4668 return VRQuals;
4669}
John McCall52872982010-11-13 05:51:15 +00004670
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004671namespace {
John McCall52872982010-11-13 05:51:15 +00004672
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004673/// \brief Helper class to manage the addition of builtin operator overload
4674/// candidates. It provides shared state and utility methods used throughout
4675/// the process, as well as a helper method to add each group of builtin
4676/// operator overloads from the standard to a candidate set.
4677class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004678 // Common instance state available to all overload candidate addition methods.
4679 Sema &S;
4680 Expr **Args;
4681 unsigned NumArgs;
4682 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004683 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004684 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4685 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004686
Chandler Carruthc6586e52010-12-12 10:35:00 +00004687 // Define some constants used to index and iterate over the arithemetic types
4688 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004689 // The "promoted arithmetic types" are the arithmetic
4690 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004691 static const unsigned FirstIntegralType = 3;
4692 static const unsigned LastIntegralType = 18;
4693 static const unsigned FirstPromotedIntegralType = 3,
4694 LastPromotedIntegralType = 9;
4695 static const unsigned FirstPromotedArithmeticType = 0,
4696 LastPromotedArithmeticType = 9;
4697 static const unsigned NumArithmeticTypes = 18;
4698
Chandler Carruthc6586e52010-12-12 10:35:00 +00004699 /// \brief Get the canonical type for a given arithmetic type index.
4700 CanQualType getArithmeticType(unsigned index) {
4701 assert(index < NumArithmeticTypes);
4702 static CanQualType ASTContext::* const
4703 ArithmeticTypes[NumArithmeticTypes] = {
4704 // Start of promoted types.
4705 &ASTContext::FloatTy,
4706 &ASTContext::DoubleTy,
4707 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004708
Chandler Carruthc6586e52010-12-12 10:35:00 +00004709 // Start of integral types.
4710 &ASTContext::IntTy,
4711 &ASTContext::LongTy,
4712 &ASTContext::LongLongTy,
4713 &ASTContext::UnsignedIntTy,
4714 &ASTContext::UnsignedLongTy,
4715 &ASTContext::UnsignedLongLongTy,
4716 // End of promoted types.
4717
4718 &ASTContext::BoolTy,
4719 &ASTContext::CharTy,
4720 &ASTContext::WCharTy,
4721 &ASTContext::Char16Ty,
4722 &ASTContext::Char32Ty,
4723 &ASTContext::SignedCharTy,
4724 &ASTContext::ShortTy,
4725 &ASTContext::UnsignedCharTy,
4726 &ASTContext::UnsignedShortTy,
4727 // End of integral types.
4728 // FIXME: What about complex?
4729 };
4730 return S.Context.*ArithmeticTypes[index];
4731 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004732
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004733 /// \brief Gets the canonical type resulting from the usual arithemetic
4734 /// converions for the given arithmetic types.
4735 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4736 // Accelerator table for performing the usual arithmetic conversions.
4737 // The rules are basically:
4738 // - if either is floating-point, use the wider floating-point
4739 // - if same signedness, use the higher rank
4740 // - if same size, use unsigned of the higher rank
4741 // - use the larger type
4742 // These rules, together with the axiom that higher ranks are
4743 // never smaller, are sufficient to precompute all of these results
4744 // *except* when dealing with signed types of higher rank.
4745 // (we could precompute SLL x UI for all known platforms, but it's
4746 // better not to make any assumptions).
4747 enum PromotedType {
4748 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4749 };
4750 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4751 [LastPromotedArithmeticType] = {
4752 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4753 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4754 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4755 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4756 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4757 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4758 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4759 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4760 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4761 };
4762
4763 assert(L < LastPromotedArithmeticType);
4764 assert(R < LastPromotedArithmeticType);
4765 int Idx = ConversionsTable[L][R];
4766
4767 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004768 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004769
4770 // Slow path: we need to compare widths.
4771 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004772 CanQualType LT = getArithmeticType(L),
4773 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004774 unsigned LW = S.Context.getIntWidth(LT),
4775 RW = S.Context.getIntWidth(RT);
4776
4777 // If they're different widths, use the signed type.
4778 if (LW > RW) return LT;
4779 else if (LW < RW) return RT;
4780
4781 // Otherwise, use the unsigned type of the signed type's rank.
4782 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4783 assert(L == SLL || R == SLL);
4784 return S.Context.UnsignedLongLongTy;
4785 }
4786
Chandler Carruth5659c0c2010-12-12 09:22:45 +00004787 /// \brief Helper method to factor out the common pattern of adding overloads
4788 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004789 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4790 bool HasVolatile) {
4791 QualType ParamTypes[2] = {
4792 S.Context.getLValueReferenceType(CandidateTy),
4793 S.Context.IntTy
4794 };
4795
4796 // Non-volatile version.
4797 if (NumArgs == 1)
4798 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4799 else
4800 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4801
4802 // Use a heuristic to reduce number of builtin candidates in the set:
4803 // add volatile version only if there are conversions to a volatile type.
4804 if (HasVolatile) {
4805 ParamTypes[0] =
4806 S.Context.getLValueReferenceType(
4807 S.Context.getVolatileType(CandidateTy));
4808 if (NumArgs == 1)
4809 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4810 else
4811 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4812 }
4813 }
4814
4815public:
4816 BuiltinOperatorOverloadBuilder(
4817 Sema &S, Expr **Args, unsigned NumArgs,
4818 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00004819 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004820 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4821 OverloadCandidateSet &CandidateSet)
4822 : S(S), Args(Args), NumArgs(NumArgs),
4823 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00004824 HasArithmeticOrEnumeralCandidateType(
4825 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004826 CandidateTypes(CandidateTypes),
4827 CandidateSet(CandidateSet) {
4828 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004829 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004830 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004831 assert(getArithmeticType(LastPromotedIntegralType - 1)
4832 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004833 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004834 assert(getArithmeticType(FirstPromotedArithmeticType)
4835 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004836 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004837 assert(getArithmeticType(LastPromotedArithmeticType - 1)
4838 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004839 "Invalid last promoted arithmetic type");
4840 }
4841
4842 // C++ [over.built]p3:
4843 //
4844 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4845 // is either volatile or empty, there exist candidate operator
4846 // functions of the form
4847 //
4848 // VQ T& operator++(VQ T&);
4849 // T operator++(VQ T&, int);
4850 //
4851 // C++ [over.built]p4:
4852 //
4853 // For every pair (T, VQ), where T is an arithmetic type other
4854 // than bool, and VQ is either volatile or empty, there exist
4855 // candidate operator functions of the form
4856 //
4857 // VQ T& operator--(VQ T&);
4858 // T operator--(VQ T&, int);
4859 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004860 if (!HasArithmeticOrEnumeralCandidateType)
4861 return;
4862
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004863 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4864 Arith < NumArithmeticTypes; ++Arith) {
4865 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00004866 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004867 VisibleTypeConversionsQuals.hasVolatile());
4868 }
4869 }
4870
4871 // C++ [over.built]p5:
4872 //
4873 // For every pair (T, VQ), where T is a cv-qualified or
4874 // cv-unqualified object type, and VQ is either volatile or
4875 // empty, there exist candidate operator functions of the form
4876 //
4877 // T*VQ& operator++(T*VQ&);
4878 // T*VQ& operator--(T*VQ&);
4879 // T* operator++(T*VQ&, int);
4880 // T* operator--(T*VQ&, int);
4881 void addPlusPlusMinusMinusPointerOverloads() {
4882 for (BuiltinCandidateTypeSet::iterator
4883 Ptr = CandidateTypes[0].pointer_begin(),
4884 PtrEnd = CandidateTypes[0].pointer_end();
4885 Ptr != PtrEnd; ++Ptr) {
4886 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00004887 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004888 continue;
4889
4890 addPlusPlusMinusMinusStyleOverloads(*Ptr,
4891 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4892 VisibleTypeConversionsQuals.hasVolatile()));
4893 }
4894 }
4895
4896 // C++ [over.built]p6:
4897 // For every cv-qualified or cv-unqualified object type T, there
4898 // exist candidate operator functions of the form
4899 //
4900 // T& operator*(T*);
4901 //
4902 // C++ [over.built]p7:
4903 // For every function type T, there exist candidate operator
4904 // functions of the form
4905 // T& operator*(T*);
4906 void addUnaryStarPointerOverloads() {
4907 for (BuiltinCandidateTypeSet::iterator
4908 Ptr = CandidateTypes[0].pointer_begin(),
4909 PtrEnd = CandidateTypes[0].pointer_end();
4910 Ptr != PtrEnd; ++Ptr) {
4911 QualType ParamTy = *Ptr;
4912 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00004913 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
4914 continue;
4915
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004916 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
4917 &ParamTy, Args, 1, CandidateSet);
4918 }
4919 }
4920
4921 // C++ [over.built]p9:
4922 // For every promoted arithmetic type T, there exist candidate
4923 // operator functions of the form
4924 //
4925 // T operator+(T);
4926 // T operator-(T);
4927 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00004928 if (!HasArithmeticOrEnumeralCandidateType)
4929 return;
4930
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004931 for (unsigned Arith = FirstPromotedArithmeticType;
4932 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004933 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004934 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4935 }
4936
4937 // Extension: We also add these operators for vector types.
4938 for (BuiltinCandidateTypeSet::iterator
4939 Vec = CandidateTypes[0].vector_begin(),
4940 VecEnd = CandidateTypes[0].vector_end();
4941 Vec != VecEnd; ++Vec) {
4942 QualType VecTy = *Vec;
4943 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4944 }
4945 }
4946
4947 // C++ [over.built]p8:
4948 // For every type T, there exist candidate operator functions of
4949 // the form
4950 //
4951 // T* operator+(T*);
4952 void addUnaryPlusPointerOverloads() {
4953 for (BuiltinCandidateTypeSet::iterator
4954 Ptr = CandidateTypes[0].pointer_begin(),
4955 PtrEnd = CandidateTypes[0].pointer_end();
4956 Ptr != PtrEnd; ++Ptr) {
4957 QualType ParamTy = *Ptr;
4958 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4959 }
4960 }
4961
4962 // C++ [over.built]p10:
4963 // For every promoted integral type T, there exist candidate
4964 // operator functions of the form
4965 //
4966 // T operator~(T);
4967 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00004968 if (!HasArithmeticOrEnumeralCandidateType)
4969 return;
4970
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004971 for (unsigned Int = FirstPromotedIntegralType;
4972 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004973 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004974 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4975 }
4976
4977 // Extension: We also add this operator for vector types.
4978 for (BuiltinCandidateTypeSet::iterator
4979 Vec = CandidateTypes[0].vector_begin(),
4980 VecEnd = CandidateTypes[0].vector_end();
4981 Vec != VecEnd; ++Vec) {
4982 QualType VecTy = *Vec;
4983 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4984 }
4985 }
4986
4987 // C++ [over.match.oper]p16:
4988 // For every pointer to member type T, there exist candidate operator
4989 // functions of the form
4990 //
4991 // bool operator==(T,T);
4992 // bool operator!=(T,T);
4993 void addEqualEqualOrNotEqualMemberPointerOverloads() {
4994 /// Set of (canonical) types that we've already handled.
4995 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4996
4997 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4998 for (BuiltinCandidateTypeSet::iterator
4999 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5000 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5001 MemPtr != MemPtrEnd;
5002 ++MemPtr) {
5003 // Don't add the same builtin candidate twice.
5004 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5005 continue;
5006
5007 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5008 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5009 CandidateSet);
5010 }
5011 }
5012 }
5013
5014 // C++ [over.built]p15:
5015 //
5016 // For every pointer or enumeration type T, there exist
5017 // candidate operator functions of the form
5018 //
5019 // bool operator<(T, T);
5020 // bool operator>(T, T);
5021 // bool operator<=(T, T);
5022 // bool operator>=(T, T);
5023 // bool operator==(T, T);
5024 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005025 void addRelationalPointerOrEnumeralOverloads() {
5026 // C++ [over.built]p1:
5027 // If there is a user-written candidate with the same name and parameter
5028 // types as a built-in candidate operator function, the built-in operator
5029 // function is hidden and is not included in the set of candidate
5030 // functions.
5031 //
5032 // The text is actually in a note, but if we don't implement it then we end
5033 // up with ambiguities when the user provides an overloaded operator for
5034 // an enumeration type. Note that only enumeration types have this problem,
5035 // so we track which enumeration types we've seen operators for. Also, the
5036 // only other overloaded operator with enumeration argumenst, operator=,
5037 // cannot be overloaded for enumeration types, so this is the only place
5038 // where we must suppress candidates like this.
5039 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5040 UserDefinedBinaryOperators;
5041
5042 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5043 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5044 CandidateTypes[ArgIdx].enumeration_end()) {
5045 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5046 CEnd = CandidateSet.end();
5047 C != CEnd; ++C) {
5048 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5049 continue;
5050
5051 QualType FirstParamType =
5052 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5053 QualType SecondParamType =
5054 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5055
5056 // Skip if either parameter isn't of enumeral type.
5057 if (!FirstParamType->isEnumeralType() ||
5058 !SecondParamType->isEnumeralType())
5059 continue;
5060
5061 // Add this operator to the set of known user-defined operators.
5062 UserDefinedBinaryOperators.insert(
5063 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5064 S.Context.getCanonicalType(SecondParamType)));
5065 }
5066 }
5067 }
5068
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005069 /// Set of (canonical) types that we've already handled.
5070 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5071
5072 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5073 for (BuiltinCandidateTypeSet::iterator
5074 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5075 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5076 Ptr != PtrEnd; ++Ptr) {
5077 // Don't add the same builtin candidate twice.
5078 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5079 continue;
5080
5081 QualType ParamTypes[2] = { *Ptr, *Ptr };
5082 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5083 CandidateSet);
5084 }
5085 for (BuiltinCandidateTypeSet::iterator
5086 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5087 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5088 Enum != EnumEnd; ++Enum) {
5089 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5090
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005091 // Don't add the same builtin candidate twice, or if a user defined
5092 // candidate exists.
5093 if (!AddedTypes.insert(CanonType) ||
5094 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5095 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005096 continue;
5097
5098 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005099 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5100 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005101 }
5102 }
5103 }
5104
5105 // C++ [over.built]p13:
5106 //
5107 // For every cv-qualified or cv-unqualified object type T
5108 // there exist candidate operator functions of the form
5109 //
5110 // T* operator+(T*, ptrdiff_t);
5111 // T& operator[](T*, ptrdiff_t); [BELOW]
5112 // T* operator-(T*, ptrdiff_t);
5113 // T* operator+(ptrdiff_t, T*);
5114 // T& operator[](ptrdiff_t, T*); [BELOW]
5115 //
5116 // C++ [over.built]p14:
5117 //
5118 // For every T, where T is a pointer to object type, there
5119 // exist candidate operator functions of the form
5120 //
5121 // ptrdiff_t operator-(T, T);
5122 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5123 /// Set of (canonical) types that we've already handled.
5124 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5125
5126 for (int Arg = 0; Arg < 2; ++Arg) {
5127 QualType AsymetricParamTypes[2] = {
5128 S.Context.getPointerDiffType(),
5129 S.Context.getPointerDiffType(),
5130 };
5131 for (BuiltinCandidateTypeSet::iterator
5132 Ptr = CandidateTypes[Arg].pointer_begin(),
5133 PtrEnd = CandidateTypes[Arg].pointer_end();
5134 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005135 QualType PointeeTy = (*Ptr)->getPointeeType();
5136 if (!PointeeTy->isObjectType())
5137 continue;
5138
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005139 AsymetricParamTypes[Arg] = *Ptr;
5140 if (Arg == 0 || Op == OO_Plus) {
5141 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5142 // T* operator+(ptrdiff_t, T*);
5143 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5144 CandidateSet);
5145 }
5146 if (Op == OO_Minus) {
5147 // ptrdiff_t operator-(T, T);
5148 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5149 continue;
5150
5151 QualType ParamTypes[2] = { *Ptr, *Ptr };
5152 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5153 Args, 2, CandidateSet);
5154 }
5155 }
5156 }
5157 }
5158
5159 // C++ [over.built]p12:
5160 //
5161 // For every pair of promoted arithmetic types L and R, there
5162 // exist candidate operator functions of the form
5163 //
5164 // LR operator*(L, R);
5165 // LR operator/(L, R);
5166 // LR operator+(L, R);
5167 // LR operator-(L, R);
5168 // bool operator<(L, R);
5169 // bool operator>(L, R);
5170 // bool operator<=(L, R);
5171 // bool operator>=(L, R);
5172 // bool operator==(L, R);
5173 // bool operator!=(L, R);
5174 //
5175 // where LR is the result of the usual arithmetic conversions
5176 // between types L and R.
5177 //
5178 // C++ [over.built]p24:
5179 //
5180 // For every pair of promoted arithmetic types L and R, there exist
5181 // candidate operator functions of the form
5182 //
5183 // LR operator?(bool, L, R);
5184 //
5185 // where LR is the result of the usual arithmetic conversions
5186 // between types L and R.
5187 // Our candidates ignore the first parameter.
5188 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005189 if (!HasArithmeticOrEnumeralCandidateType)
5190 return;
5191
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005192 for (unsigned Left = FirstPromotedArithmeticType;
5193 Left < LastPromotedArithmeticType; ++Left) {
5194 for (unsigned Right = FirstPromotedArithmeticType;
5195 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005196 QualType LandR[2] = { getArithmeticType(Left),
5197 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005198 QualType Result =
5199 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005200 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005201 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5202 }
5203 }
5204
5205 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5206 // conditional operator for vector types.
5207 for (BuiltinCandidateTypeSet::iterator
5208 Vec1 = CandidateTypes[0].vector_begin(),
5209 Vec1End = CandidateTypes[0].vector_end();
5210 Vec1 != Vec1End; ++Vec1) {
5211 for (BuiltinCandidateTypeSet::iterator
5212 Vec2 = CandidateTypes[1].vector_begin(),
5213 Vec2End = CandidateTypes[1].vector_end();
5214 Vec2 != Vec2End; ++Vec2) {
5215 QualType LandR[2] = { *Vec1, *Vec2 };
5216 QualType Result = S.Context.BoolTy;
5217 if (!isComparison) {
5218 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5219 Result = *Vec1;
5220 else
5221 Result = *Vec2;
5222 }
5223
5224 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5225 }
5226 }
5227 }
5228
5229 // C++ [over.built]p17:
5230 //
5231 // For every pair of promoted integral types L and R, there
5232 // exist candidate operator functions of the form
5233 //
5234 // LR operator%(L, R);
5235 // LR operator&(L, R);
5236 // LR operator^(L, R);
5237 // LR operator|(L, R);
5238 // L operator<<(L, R);
5239 // L operator>>(L, R);
5240 //
5241 // where LR is the result of the usual arithmetic conversions
5242 // between types L and R.
5243 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005244 if (!HasArithmeticOrEnumeralCandidateType)
5245 return;
5246
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005247 for (unsigned Left = FirstPromotedIntegralType;
5248 Left < LastPromotedIntegralType; ++Left) {
5249 for (unsigned Right = FirstPromotedIntegralType;
5250 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005251 QualType LandR[2] = { getArithmeticType(Left),
5252 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005253 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5254 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005255 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005256 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5257 }
5258 }
5259 }
5260
5261 // C++ [over.built]p20:
5262 //
5263 // For every pair (T, VQ), where T is an enumeration or
5264 // pointer to member type and VQ is either volatile or
5265 // empty, there exist candidate operator functions of the form
5266 //
5267 // VQ T& operator=(VQ T&, T);
5268 void addAssignmentMemberPointerOrEnumeralOverloads() {
5269 /// Set of (canonical) types that we've already handled.
5270 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5271
5272 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5273 for (BuiltinCandidateTypeSet::iterator
5274 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5275 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5276 Enum != EnumEnd; ++Enum) {
5277 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5278 continue;
5279
5280 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5281 CandidateSet);
5282 }
5283
5284 for (BuiltinCandidateTypeSet::iterator
5285 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5286 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5287 MemPtr != MemPtrEnd; ++MemPtr) {
5288 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5289 continue;
5290
5291 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5292 CandidateSet);
5293 }
5294 }
5295 }
5296
5297 // C++ [over.built]p19:
5298 //
5299 // For every pair (T, VQ), where T is any type and VQ is either
5300 // volatile or empty, there exist candidate operator functions
5301 // of the form
5302 //
5303 // T*VQ& operator=(T*VQ&, T*);
5304 //
5305 // C++ [over.built]p21:
5306 //
5307 // For every pair (T, VQ), where T is a cv-qualified or
5308 // cv-unqualified object type and VQ is either volatile or
5309 // empty, there exist candidate operator functions of the form
5310 //
5311 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5312 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5313 void addAssignmentPointerOverloads(bool isEqualOp) {
5314 /// Set of (canonical) types that we've already handled.
5315 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5316
5317 for (BuiltinCandidateTypeSet::iterator
5318 Ptr = CandidateTypes[0].pointer_begin(),
5319 PtrEnd = CandidateTypes[0].pointer_end();
5320 Ptr != PtrEnd; ++Ptr) {
5321 // If this is operator=, keep track of the builtin candidates we added.
5322 if (isEqualOp)
5323 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005324 else if (!(*Ptr)->getPointeeType()->isObjectType())
5325 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005326
5327 // non-volatile version
5328 QualType ParamTypes[2] = {
5329 S.Context.getLValueReferenceType(*Ptr),
5330 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5331 };
5332 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5333 /*IsAssigmentOperator=*/ isEqualOp);
5334
5335 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5336 VisibleTypeConversionsQuals.hasVolatile()) {
5337 // volatile version
5338 ParamTypes[0] =
5339 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5340 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5341 /*IsAssigmentOperator=*/isEqualOp);
5342 }
5343 }
5344
5345 if (isEqualOp) {
5346 for (BuiltinCandidateTypeSet::iterator
5347 Ptr = CandidateTypes[1].pointer_begin(),
5348 PtrEnd = CandidateTypes[1].pointer_end();
5349 Ptr != PtrEnd; ++Ptr) {
5350 // Make sure we don't add the same candidate twice.
5351 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5352 continue;
5353
Chandler Carruth8e543b32010-12-12 08:17:55 +00005354 QualType ParamTypes[2] = {
5355 S.Context.getLValueReferenceType(*Ptr),
5356 *Ptr,
5357 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005358
5359 // non-volatile version
5360 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5361 /*IsAssigmentOperator=*/true);
5362
5363 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5364 VisibleTypeConversionsQuals.hasVolatile()) {
5365 // volatile version
5366 ParamTypes[0] =
5367 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005368 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5369 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005370 }
5371 }
5372 }
5373 }
5374
5375 // C++ [over.built]p18:
5376 //
5377 // For every triple (L, VQ, R), where L is an arithmetic type,
5378 // VQ is either volatile or empty, and R is a promoted
5379 // arithmetic type, there exist candidate operator functions of
5380 // the form
5381 //
5382 // VQ L& operator=(VQ L&, R);
5383 // VQ L& operator*=(VQ L&, R);
5384 // VQ L& operator/=(VQ L&, R);
5385 // VQ L& operator+=(VQ L&, R);
5386 // VQ L& operator-=(VQ L&, R);
5387 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005388 if (!HasArithmeticOrEnumeralCandidateType)
5389 return;
5390
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005391 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5392 for (unsigned Right = FirstPromotedArithmeticType;
5393 Right < LastPromotedArithmeticType; ++Right) {
5394 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005395 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005396
5397 // Add this built-in operator as a candidate (VQ is empty).
5398 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005399 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005400 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5401 /*IsAssigmentOperator=*/isEqualOp);
5402
5403 // Add this built-in operator as a candidate (VQ is 'volatile').
5404 if (VisibleTypeConversionsQuals.hasVolatile()) {
5405 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005406 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005407 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005408 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5409 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005410 /*IsAssigmentOperator=*/isEqualOp);
5411 }
5412 }
5413 }
5414
5415 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5416 for (BuiltinCandidateTypeSet::iterator
5417 Vec1 = CandidateTypes[0].vector_begin(),
5418 Vec1End = CandidateTypes[0].vector_end();
5419 Vec1 != Vec1End; ++Vec1) {
5420 for (BuiltinCandidateTypeSet::iterator
5421 Vec2 = CandidateTypes[1].vector_begin(),
5422 Vec2End = CandidateTypes[1].vector_end();
5423 Vec2 != Vec2End; ++Vec2) {
5424 QualType ParamTypes[2];
5425 ParamTypes[1] = *Vec2;
5426 // Add this built-in operator as a candidate (VQ is empty).
5427 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5428 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5429 /*IsAssigmentOperator=*/isEqualOp);
5430
5431 // Add this built-in operator as a candidate (VQ is 'volatile').
5432 if (VisibleTypeConversionsQuals.hasVolatile()) {
5433 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5434 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005435 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5436 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005437 /*IsAssigmentOperator=*/isEqualOp);
5438 }
5439 }
5440 }
5441 }
5442
5443 // C++ [over.built]p22:
5444 //
5445 // For every triple (L, VQ, R), where L is an integral type, VQ
5446 // is either volatile or empty, and R is a promoted integral
5447 // type, there exist candidate operator functions of the form
5448 //
5449 // VQ L& operator%=(VQ L&, R);
5450 // VQ L& operator<<=(VQ L&, R);
5451 // VQ L& operator>>=(VQ L&, R);
5452 // VQ L& operator&=(VQ L&, R);
5453 // VQ L& operator^=(VQ L&, R);
5454 // VQ L& operator|=(VQ L&, R);
5455 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005456 if (!HasArithmeticOrEnumeralCandidateType)
5457 return;
5458
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005459 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5460 for (unsigned Right = FirstPromotedIntegralType;
5461 Right < LastPromotedIntegralType; ++Right) {
5462 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005463 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005464
5465 // Add this built-in operator as a candidate (VQ is empty).
5466 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005467 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005468 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5469 if (VisibleTypeConversionsQuals.hasVolatile()) {
5470 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005471 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005472 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5473 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5474 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5475 CandidateSet);
5476 }
5477 }
5478 }
5479 }
5480
5481 // C++ [over.operator]p23:
5482 //
5483 // There also exist candidate operator functions of the form
5484 //
5485 // bool operator!(bool);
5486 // bool operator&&(bool, bool);
5487 // bool operator||(bool, bool);
5488 void addExclaimOverload() {
5489 QualType ParamTy = S.Context.BoolTy;
5490 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5491 /*IsAssignmentOperator=*/false,
5492 /*NumContextualBoolArguments=*/1);
5493 }
5494 void addAmpAmpOrPipePipeOverload() {
5495 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5496 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5497 /*IsAssignmentOperator=*/false,
5498 /*NumContextualBoolArguments=*/2);
5499 }
5500
5501 // C++ [over.built]p13:
5502 //
5503 // For every cv-qualified or cv-unqualified object type T there
5504 // exist candidate operator functions of the form
5505 //
5506 // T* operator+(T*, ptrdiff_t); [ABOVE]
5507 // T& operator[](T*, ptrdiff_t);
5508 // T* operator-(T*, ptrdiff_t); [ABOVE]
5509 // T* operator+(ptrdiff_t, T*); [ABOVE]
5510 // T& operator[](ptrdiff_t, T*);
5511 void addSubscriptOverloads() {
5512 for (BuiltinCandidateTypeSet::iterator
5513 Ptr = CandidateTypes[0].pointer_begin(),
5514 PtrEnd = CandidateTypes[0].pointer_end();
5515 Ptr != PtrEnd; ++Ptr) {
5516 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5517 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005518 if (!PointeeType->isObjectType())
5519 continue;
5520
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005521 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5522
5523 // T& operator[](T*, ptrdiff_t)
5524 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5525 }
5526
5527 for (BuiltinCandidateTypeSet::iterator
5528 Ptr = CandidateTypes[1].pointer_begin(),
5529 PtrEnd = CandidateTypes[1].pointer_end();
5530 Ptr != PtrEnd; ++Ptr) {
5531 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5532 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005533 if (!PointeeType->isObjectType())
5534 continue;
5535
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005536 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5537
5538 // T& operator[](ptrdiff_t, T*)
5539 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5540 }
5541 }
5542
5543 // C++ [over.built]p11:
5544 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5545 // C1 is the same type as C2 or is a derived class of C2, T is an object
5546 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5547 // there exist candidate operator functions of the form
5548 //
5549 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5550 //
5551 // where CV12 is the union of CV1 and CV2.
5552 void addArrowStarOverloads() {
5553 for (BuiltinCandidateTypeSet::iterator
5554 Ptr = CandidateTypes[0].pointer_begin(),
5555 PtrEnd = CandidateTypes[0].pointer_end();
5556 Ptr != PtrEnd; ++Ptr) {
5557 QualType C1Ty = (*Ptr);
5558 QualType C1;
5559 QualifierCollector Q1;
5560 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5561 if (!isa<RecordType>(C1))
5562 continue;
5563 // heuristic to reduce number of builtin candidates in the set.
5564 // Add volatile/restrict version only if there are conversions to a
5565 // volatile/restrict type.
5566 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5567 continue;
5568 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5569 continue;
5570 for (BuiltinCandidateTypeSet::iterator
5571 MemPtr = CandidateTypes[1].member_pointer_begin(),
5572 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5573 MemPtr != MemPtrEnd; ++MemPtr) {
5574 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5575 QualType C2 = QualType(mptr->getClass(), 0);
5576 C2 = C2.getUnqualifiedType();
5577 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5578 break;
5579 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5580 // build CV12 T&
5581 QualType T = mptr->getPointeeType();
5582 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5583 T.isVolatileQualified())
5584 continue;
5585 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5586 T.isRestrictQualified())
5587 continue;
5588 T = Q1.apply(S.Context, T);
5589 QualType ResultTy = S.Context.getLValueReferenceType(T);
5590 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5591 }
5592 }
5593 }
5594
5595 // Note that we don't consider the first argument, since it has been
5596 // contextually converted to bool long ago. The candidates below are
5597 // therefore added as binary.
5598 //
5599 // C++ [over.built]p25:
5600 // For every type T, where T is a pointer, pointer-to-member, or scoped
5601 // enumeration type, there exist candidate operator functions of the form
5602 //
5603 // T operator?(bool, T, T);
5604 //
5605 void addConditionalOperatorOverloads() {
5606 /// Set of (canonical) types that we've already handled.
5607 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5608
5609 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5610 for (BuiltinCandidateTypeSet::iterator
5611 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5612 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5613 Ptr != PtrEnd; ++Ptr) {
5614 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5615 continue;
5616
5617 QualType ParamTypes[2] = { *Ptr, *Ptr };
5618 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5619 }
5620
5621 for (BuiltinCandidateTypeSet::iterator
5622 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5623 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5624 MemPtr != MemPtrEnd; ++MemPtr) {
5625 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5626 continue;
5627
5628 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5629 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5630 }
5631
5632 if (S.getLangOptions().CPlusPlus0x) {
5633 for (BuiltinCandidateTypeSet::iterator
5634 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5635 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5636 Enum != EnumEnd; ++Enum) {
5637 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5638 continue;
5639
5640 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5641 continue;
5642
5643 QualType ParamTypes[2] = { *Enum, *Enum };
5644 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5645 }
5646 }
5647 }
5648 }
5649};
5650
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005651} // end anonymous namespace
5652
5653/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5654/// operator overloads to the candidate set (C++ [over.built]), based
5655/// on the operator @p Op and the arguments given. For example, if the
5656/// operator is a binary '+', this routine might add "int
5657/// operator+(int, int)" to cover integer addition.
5658void
5659Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5660 SourceLocation OpLoc,
5661 Expr **Args, unsigned NumArgs,
5662 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005663 // Find all of the types that the arguments can convert to, but only
5664 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005665 // that make use of these types. Also record whether we encounter non-record
5666 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005667 Qualifiers VisibleTypeConversionsQuals;
5668 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005669 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5670 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005671
5672 bool HasNonRecordCandidateType = false;
5673 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005674 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5675 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5676 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5677 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5678 OpLoc,
5679 true,
5680 (Op == OO_Exclaim ||
5681 Op == OO_AmpAmp ||
5682 Op == OO_PipePipe),
5683 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005684 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5685 CandidateTypes[ArgIdx].hasNonRecordTypes();
5686 HasArithmeticOrEnumeralCandidateType =
5687 HasArithmeticOrEnumeralCandidateType ||
5688 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005689 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005690
Chandler Carruth00a38332010-12-13 01:44:01 +00005691 // Exit early when no non-record types have been added to the candidate set
5692 // for any of the arguments to the operator.
5693 if (!HasNonRecordCandidateType)
5694 return;
5695
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005696 // Setup an object to manage the common state for building overloads.
5697 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5698 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005699 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005700 CandidateTypes, CandidateSet);
5701
5702 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005703 switch (Op) {
5704 case OO_None:
5705 case NUM_OVERLOADED_OPERATORS:
5706 assert(false && "Expected an overloaded operator");
5707 break;
5708
Chandler Carruth5184de02010-12-12 08:51:33 +00005709 case OO_New:
5710 case OO_Delete:
5711 case OO_Array_New:
5712 case OO_Array_Delete:
5713 case OO_Call:
5714 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5715 break;
5716
5717 case OO_Comma:
5718 case OO_Arrow:
5719 // C++ [over.match.oper]p3:
5720 // -- For the operator ',', the unary operator '&', or the
5721 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00005722 break;
5723
5724 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005725 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005726 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005727 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00005728
5729 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00005730 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005731 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005732 } else {
5733 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5734 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5735 }
Douglas Gregord08452f2008-11-19 15:42:04 +00005736 break;
5737
Chandler Carruth5184de02010-12-12 08:51:33 +00005738 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00005739 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00005740 OpBuilder.addUnaryStarPointerOverloads();
5741 else
5742 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5743 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005744
Chandler Carruth5184de02010-12-12 08:51:33 +00005745 case OO_Slash:
5746 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005747 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005748
5749 case OO_PlusPlus:
5750 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005751 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5752 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005753 break;
5754
Douglas Gregor84605ae2009-08-24 13:43:27 +00005755 case OO_EqualEqual:
5756 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005757 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005758 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005759
Douglas Gregora11693b2008-11-12 17:17:38 +00005760 case OO_Less:
5761 case OO_Greater:
5762 case OO_LessEqual:
5763 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005764 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005765 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5766 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005767
Douglas Gregora11693b2008-11-12 17:17:38 +00005768 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00005769 case OO_Caret:
5770 case OO_Pipe:
5771 case OO_LessLess:
5772 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005773 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00005774 break;
5775
Chandler Carruth5184de02010-12-12 08:51:33 +00005776 case OO_Amp: // '&' is either unary or binary
5777 if (NumArgs == 1)
5778 // C++ [over.match.oper]p3:
5779 // -- For the operator ',', the unary operator '&', or the
5780 // operator '->', the built-in candidates set is empty.
5781 break;
5782
5783 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5784 break;
5785
5786 case OO_Tilde:
5787 OpBuilder.addUnaryTildePromotedIntegralOverloads();
5788 break;
5789
Douglas Gregora11693b2008-11-12 17:17:38 +00005790 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005791 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005792 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005793
5794 case OO_PlusEqual:
5795 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005796 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005797 // Fall through.
5798
5799 case OO_StarEqual:
5800 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005801 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005802 break;
5803
5804 case OO_PercentEqual:
5805 case OO_LessLessEqual:
5806 case OO_GreaterGreaterEqual:
5807 case OO_AmpEqual:
5808 case OO_CaretEqual:
5809 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005810 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005811 break;
5812
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005813 case OO_Exclaim:
5814 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00005815 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005816
Douglas Gregora11693b2008-11-12 17:17:38 +00005817 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005818 case OO_PipePipe:
5819 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00005820 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005821
5822 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005823 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005824 break;
5825
5826 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005827 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005828 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005829
5830 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005831 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005832 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5833 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005834 }
5835}
5836
Douglas Gregore254f902009-02-04 00:32:51 +00005837/// \brief Add function candidates found via argument-dependent lookup
5838/// to the set of overloading candidates.
5839///
5840/// This routine performs argument-dependent name lookup based on the
5841/// given function name (which may also be an operator name) and adds
5842/// all of the overload candidates found by ADL to the overload
5843/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005844void
Douglas Gregore254f902009-02-04 00:32:51 +00005845Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005846 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005847 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005848 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005849 OverloadCandidateSet& CandidateSet,
5850 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005851 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005852
John McCall91f61fc2010-01-26 06:04:06 +00005853 // FIXME: This approach for uniquing ADL results (and removing
5854 // redundant candidates from the set) relies on pointer-equality,
5855 // which means we need to key off the canonical decl. However,
5856 // always going back to the canonical decl might not get us the
5857 // right set of default arguments. What default arguments are
5858 // we supposed to consider on ADL candidates, anyway?
5859
Douglas Gregorcabea402009-09-22 15:41:20 +00005860 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005861 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005862
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005863 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005864 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5865 CandEnd = CandidateSet.end();
5866 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005867 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005868 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005869 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005870 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005871 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005872
5873 // For each of the ADL candidates we found, add it to the overload
5874 // set.
John McCall8fe68082010-01-26 07:16:45 +00005875 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005876 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005877 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005878 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005879 continue;
5880
John McCalla0296f72010-03-19 07:35:19 +00005881 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005882 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005883 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005884 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005885 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005886 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005887 }
Douglas Gregore254f902009-02-04 00:32:51 +00005888}
5889
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005890/// isBetterOverloadCandidate - Determines whether the first overload
5891/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005892bool
John McCall5c32be02010-08-24 20:38:10 +00005893isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005894 const OverloadCandidate &Cand1,
5895 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005896 SourceLocation Loc,
5897 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005898 // Define viable functions to be better candidates than non-viable
5899 // functions.
5900 if (!Cand2.Viable)
5901 return Cand1.Viable;
5902 else if (!Cand1.Viable)
5903 return false;
5904
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005905 // C++ [over.match.best]p1:
5906 //
5907 // -- if F is a static member function, ICS1(F) is defined such
5908 // that ICS1(F) is neither better nor worse than ICS1(G) for
5909 // any function G, and, symmetrically, ICS1(G) is neither
5910 // better nor worse than ICS1(F).
5911 unsigned StartArg = 0;
5912 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5913 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005914
Douglas Gregord3cb3562009-07-07 23:38:56 +00005915 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005916 // A viable function F1 is defined to be a better function than another
5917 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005918 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005919 unsigned NumArgs = Cand1.Conversions.size();
5920 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5921 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005922 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005923 switch (CompareImplicitConversionSequences(S,
5924 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005925 Cand2.Conversions[ArgIdx])) {
5926 case ImplicitConversionSequence::Better:
5927 // Cand1 has a better conversion sequence.
5928 HasBetterConversion = true;
5929 break;
5930
5931 case ImplicitConversionSequence::Worse:
5932 // Cand1 can't be better than Cand2.
5933 return false;
5934
5935 case ImplicitConversionSequence::Indistinguishable:
5936 // Do nothing.
5937 break;
5938 }
5939 }
5940
Mike Stump11289f42009-09-09 15:08:12 +00005941 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005942 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005943 if (HasBetterConversion)
5944 return true;
5945
Mike Stump11289f42009-09-09 15:08:12 +00005946 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005947 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005948 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005949 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5950 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005951
5952 // -- F1 and F2 are function template specializations, and the function
5953 // template for F1 is more specialized than the template for F2
5954 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005955 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005956 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00005957 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005958 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005959 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5960 Cand2.Function->getPrimaryTemplate(),
5961 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005962 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00005963 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00005964 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00005965 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00005966 }
5967
Douglas Gregora1f013e2008-11-07 22:36:19 +00005968 // -- the context is an initialization by user-defined conversion
5969 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5970 // from the return type of F1 to the destination type (i.e.,
5971 // the type of the entity being initialized) is a better
5972 // conversion sequence than the standard conversion sequence
5973 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005974 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005975 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005976 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005977 switch (CompareStandardConversionSequences(S,
5978 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005979 Cand2.FinalConversion)) {
5980 case ImplicitConversionSequence::Better:
5981 // Cand1 has a better conversion sequence.
5982 return true;
5983
5984 case ImplicitConversionSequence::Worse:
5985 // Cand1 can't be better than Cand2.
5986 return false;
5987
5988 case ImplicitConversionSequence::Indistinguishable:
5989 // Do nothing
5990 break;
5991 }
5992 }
5993
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005994 return false;
5995}
5996
Mike Stump11289f42009-09-09 15:08:12 +00005997/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005998/// within an overload candidate set.
5999///
6000/// \param CandidateSet the set of candidate functions.
6001///
6002/// \param Loc the location of the function name (or operator symbol) for
6003/// which overload resolution occurs.
6004///
Mike Stump11289f42009-09-09 15:08:12 +00006005/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006006/// function, Best points to the candidate function found.
6007///
6008/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006009OverloadingResult
6010OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006011 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006012 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006013 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006014 Best = end();
6015 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6016 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00006017 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6018 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006019 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006020 }
6021
6022 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006023 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006024 return OR_No_Viable_Function;
6025
6026 // Make sure that this function is better than every other viable
6027 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006028 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006029 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006030 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00006031 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6032 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006033 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006034 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006035 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006036 }
Mike Stump11289f42009-09-09 15:08:12 +00006037
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006038 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006039 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006040 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006041 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006042 return OR_Deleted;
6043
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006044 // C++ [basic.def.odr]p2:
6045 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00006046 // when referred to from a potentially-evaluated expression. [Note: this
6047 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006048 // (clause 13), user-defined conversions (12.3.2), allocation function for
6049 // placement new (5.3.4), as well as non-default initialization (8.5).
6050 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00006051 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006052
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006053 return OR_Success;
6054}
6055
John McCall53262c92010-01-12 02:15:36 +00006056namespace {
6057
6058enum OverloadCandidateKind {
6059 oc_function,
6060 oc_method,
6061 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006062 oc_function_template,
6063 oc_method_template,
6064 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006065 oc_implicit_default_constructor,
6066 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006067 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00006068};
6069
John McCalle1ac8d12010-01-13 00:25:19 +00006070OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6071 FunctionDecl *Fn,
6072 std::string &Description) {
6073 bool isTemplate = false;
6074
6075 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6076 isTemplate = true;
6077 Description = S.getTemplateArgumentBindingsText(
6078 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6079 }
John McCallfd0b2f82010-01-06 09:43:14 +00006080
6081 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006082 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006083 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006084
John McCall53262c92010-01-12 02:15:36 +00006085 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6086 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006087 }
6088
6089 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6090 // This actually gets spelled 'candidate function' for now, but
6091 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006092 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006093 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006094
Douglas Gregorec3bec02010-09-27 22:37:28 +00006095 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006096 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006097 return oc_implicit_copy_assignment;
6098 }
6099
John McCalle1ac8d12010-01-13 00:25:19 +00006100 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006101}
6102
6103} // end anonymous namespace
6104
6105// Notes the location of an overload candidate.
6106void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006107 std::string FnDesc;
6108 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6109 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6110 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00006111}
6112
John McCall0d1da222010-01-12 00:44:57 +00006113/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6114/// "lead" diagnostic; it will be given two arguments, the source and
6115/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006116void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6117 Sema &S,
6118 SourceLocation CaretLoc,
6119 const PartialDiagnostic &PDiag) const {
6120 S.Diag(CaretLoc, PDiag)
6121 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006122 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006123 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6124 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006125 }
John McCall12f97bc2010-01-08 04:41:39 +00006126}
6127
John McCall0d1da222010-01-12 00:44:57 +00006128namespace {
6129
John McCall6a61b522010-01-13 09:16:55 +00006130void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6131 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6132 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006133 assert(Cand->Function && "for now, candidate must be a function");
6134 FunctionDecl *Fn = Cand->Function;
6135
6136 // There's a conversion slot for the object argument if this is a
6137 // non-constructor method. Note that 'I' corresponds the
6138 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006139 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006140 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006141 if (I == 0)
6142 isObjectArgument = true;
6143 else
6144 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006145 }
6146
John McCalle1ac8d12010-01-13 00:25:19 +00006147 std::string FnDesc;
6148 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6149
John McCall6a61b522010-01-13 09:16:55 +00006150 Expr *FromExpr = Conv.Bad.FromExpr;
6151 QualType FromTy = Conv.Bad.getFromType();
6152 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006153
John McCallfb7ad0f2010-02-02 02:42:52 +00006154 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006155 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006156 Expr *E = FromExpr->IgnoreParens();
6157 if (isa<UnaryOperator>(E))
6158 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006159 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006160
6161 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6162 << (unsigned) FnKind << FnDesc
6163 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6164 << ToTy << Name << I+1;
6165 return;
6166 }
6167
John McCall6d174642010-01-23 08:10:49 +00006168 // Do some hand-waving analysis to see if the non-viability is due
6169 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006170 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6171 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6172 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6173 CToTy = RT->getPointeeType();
6174 else {
6175 // TODO: detect and diagnose the full richness of const mismatches.
6176 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6177 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6178 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6179 }
6180
6181 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6182 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6183 // It is dumb that we have to do this here.
6184 while (isa<ArrayType>(CFromTy))
6185 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6186 while (isa<ArrayType>(CToTy))
6187 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6188
6189 Qualifiers FromQs = CFromTy.getQualifiers();
6190 Qualifiers ToQs = CToTy.getQualifiers();
6191
6192 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6193 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6194 << (unsigned) FnKind << FnDesc
6195 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6196 << FromTy
6197 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6198 << (unsigned) isObjectArgument << I+1;
6199 return;
6200 }
6201
6202 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6203 assert(CVR && "unexpected qualifiers mismatch");
6204
6205 if (isObjectArgument) {
6206 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6207 << (unsigned) FnKind << FnDesc
6208 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6209 << FromTy << (CVR - 1);
6210 } else {
6211 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6212 << (unsigned) FnKind << FnDesc
6213 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6214 << FromTy << (CVR - 1) << I+1;
6215 }
6216 return;
6217 }
6218
John McCall6d174642010-01-23 08:10:49 +00006219 // Diagnose references or pointers to incomplete types differently,
6220 // since it's far from impossible that the incompleteness triggered
6221 // the failure.
6222 QualType TempFromTy = FromTy.getNonReferenceType();
6223 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6224 TempFromTy = PTy->getPointeeType();
6225 if (TempFromTy->isIncompleteType()) {
6226 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6227 << (unsigned) FnKind << FnDesc
6228 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6229 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6230 return;
6231 }
6232
Douglas Gregor56f2e342010-06-30 23:01:39 +00006233 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006234 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006235 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6236 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6237 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6238 FromPtrTy->getPointeeType()) &&
6239 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6240 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6241 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6242 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006243 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006244 }
6245 } else if (const ObjCObjectPointerType *FromPtrTy
6246 = FromTy->getAs<ObjCObjectPointerType>()) {
6247 if (const ObjCObjectPointerType *ToPtrTy
6248 = ToTy->getAs<ObjCObjectPointerType>())
6249 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6250 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6251 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6252 FromPtrTy->getPointeeType()) &&
6253 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006254 BaseToDerivedConversion = 2;
6255 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6256 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6257 !FromTy->isIncompleteType() &&
6258 !ToRefTy->getPointeeType()->isIncompleteType() &&
6259 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6260 BaseToDerivedConversion = 3;
6261 }
6262
6263 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00006264 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006265 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006266 << (unsigned) FnKind << FnDesc
6267 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006268 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006269 << FromTy << ToTy << I+1;
6270 return;
6271 }
6272
John McCall47000992010-01-14 03:28:57 +00006273 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006274 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6275 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006276 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006277 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006278}
6279
6280void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6281 unsigned NumFormalArgs) {
6282 // TODO: treat calls to a missing default constructor as a special case
6283
6284 FunctionDecl *Fn = Cand->Function;
6285 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6286
6287 unsigned MinParams = Fn->getMinRequiredArguments();
6288
6289 // at least / at most / exactly
6290 unsigned mode, modeCount;
6291 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006292 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6293 (Cand->FailureKind == ovl_fail_bad_deduction &&
6294 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
Douglas Gregor7825bf32011-01-06 22:09:01 +00006295 if (MinParams != FnTy->getNumArgs() ||
6296 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006297 mode = 0; // "at least"
6298 else
6299 mode = 2; // "exactly"
6300 modeCount = MinParams;
6301 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006302 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6303 (Cand->FailureKind == ovl_fail_bad_deduction &&
6304 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006305 if (MinParams != FnTy->getNumArgs())
6306 mode = 1; // "at most"
6307 else
6308 mode = 2; // "exactly"
6309 modeCount = FnTy->getNumArgs();
6310 }
6311
6312 std::string Description;
6313 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6314
6315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006316 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6317 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006318}
6319
John McCall8b9ed552010-02-01 18:53:26 +00006320/// Diagnose a failed template-argument deduction.
6321void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6322 Expr **Args, unsigned NumArgs) {
6323 FunctionDecl *Fn = Cand->Function; // pattern
6324
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006325 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006326 NamedDecl *ParamD;
6327 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6328 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6329 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006330 switch (Cand->DeductionFailure.Result) {
6331 case Sema::TDK_Success:
6332 llvm_unreachable("TDK_success while diagnosing bad deduction");
6333
6334 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006335 assert(ParamD && "no parameter found for incomplete deduction result");
6336 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6337 << ParamD->getDeclName();
6338 return;
6339 }
6340
John McCall42d7d192010-08-05 09:05:08 +00006341 case Sema::TDK_Underqualified: {
6342 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6343 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6344
6345 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6346
6347 // Param will have been canonicalized, but it should just be a
6348 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006349 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006350 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006351 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006352 assert(S.Context.hasSameType(Param, NonCanonParam));
6353
6354 // Arg has also been canonicalized, but there's nothing we can do
6355 // about that. It also doesn't matter as much, because it won't
6356 // have any template parameters in it (because deduction isn't
6357 // done on dependent types).
6358 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6359
6360 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6361 << ParamD->getDeclName() << Arg << NonCanonParam;
6362 return;
6363 }
6364
6365 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006366 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006367 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006368 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006369 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006370 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006371 which = 1;
6372 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006373 which = 2;
6374 }
6375
6376 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6377 << which << ParamD->getDeclName()
6378 << *Cand->DeductionFailure.getFirstArg()
6379 << *Cand->DeductionFailure.getSecondArg();
6380 return;
6381 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006382
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006383 case Sema::TDK_InvalidExplicitArguments:
6384 assert(ParamD && "no parameter found for invalid explicit arguments");
6385 if (ParamD->getDeclName())
6386 S.Diag(Fn->getLocation(),
6387 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6388 << ParamD->getDeclName();
6389 else {
6390 int index = 0;
6391 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6392 index = TTP->getIndex();
6393 else if (NonTypeTemplateParmDecl *NTTP
6394 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6395 index = NTTP->getIndex();
6396 else
6397 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6398 S.Diag(Fn->getLocation(),
6399 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6400 << (index + 1);
6401 }
6402 return;
6403
Douglas Gregor02eb4832010-05-08 18:13:28 +00006404 case Sema::TDK_TooManyArguments:
6405 case Sema::TDK_TooFewArguments:
6406 DiagnoseArityMismatch(S, Cand, NumArgs);
6407 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006408
6409 case Sema::TDK_InstantiationDepth:
6410 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6411 return;
6412
6413 case Sema::TDK_SubstitutionFailure: {
6414 std::string ArgString;
6415 if (TemplateArgumentList *Args
6416 = Cand->DeductionFailure.getTemplateArgumentList())
6417 ArgString = S.getTemplateArgumentBindingsText(
6418 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6419 *Args);
6420 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6421 << ArgString;
6422 return;
6423 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006424
John McCall8b9ed552010-02-01 18:53:26 +00006425 // TODO: diagnose these individually, then kill off
6426 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006427 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006428 case Sema::TDK_FailedOverloadResolution:
6429 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6430 return;
6431 }
6432}
6433
6434/// Generates a 'note' diagnostic for an overload candidate. We've
6435/// already generated a primary error at the call site.
6436///
6437/// It really does need to be a single diagnostic with its caret
6438/// pointed at the candidate declaration. Yes, this creates some
6439/// major challenges of technical writing. Yes, this makes pointing
6440/// out problems with specific arguments quite awkward. It's still
6441/// better than generating twenty screens of text for every failed
6442/// overload.
6443///
6444/// It would be great to be able to express per-candidate problems
6445/// more richly for those diagnostic clients that cared, but we'd
6446/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006447void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6448 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006449 FunctionDecl *Fn = Cand->Function;
6450
John McCall12f97bc2010-01-08 04:41:39 +00006451 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006452 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006453 std::string FnDesc;
6454 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006455
6456 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006457 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006458 return;
John McCall12f97bc2010-01-08 04:41:39 +00006459 }
6460
John McCalle1ac8d12010-01-13 00:25:19 +00006461 // We don't really have anything else to say about viable candidates.
6462 if (Cand->Viable) {
6463 S.NoteOverloadCandidate(Fn);
6464 return;
6465 }
John McCall0d1da222010-01-12 00:44:57 +00006466
John McCall6a61b522010-01-13 09:16:55 +00006467 switch (Cand->FailureKind) {
6468 case ovl_fail_too_many_arguments:
6469 case ovl_fail_too_few_arguments:
6470 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006471
John McCall6a61b522010-01-13 09:16:55 +00006472 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006473 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6474
John McCallfe796dd2010-01-23 05:17:32 +00006475 case ovl_fail_trivial_conversion:
6476 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006477 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006478 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006479
John McCall65eb8792010-02-25 01:37:24 +00006480 case ovl_fail_bad_conversion: {
6481 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6482 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006483 if (Cand->Conversions[I].isBad())
6484 return DiagnoseBadConversion(S, Cand, I);
6485
6486 // FIXME: this currently happens when we're called from SemaInit
6487 // when user-conversion overload fails. Figure out how to handle
6488 // those conditions and diagnose them well.
6489 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006490 }
John McCall65eb8792010-02-25 01:37:24 +00006491 }
John McCalld3224162010-01-08 00:58:21 +00006492}
6493
6494void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6495 // Desugar the type of the surrogate down to a function type,
6496 // retaining as many typedefs as possible while still showing
6497 // the function type (and, therefore, its parameter types).
6498 QualType FnType = Cand->Surrogate->getConversionType();
6499 bool isLValueReference = false;
6500 bool isRValueReference = false;
6501 bool isPointer = false;
6502 if (const LValueReferenceType *FnTypeRef =
6503 FnType->getAs<LValueReferenceType>()) {
6504 FnType = FnTypeRef->getPointeeType();
6505 isLValueReference = true;
6506 } else if (const RValueReferenceType *FnTypeRef =
6507 FnType->getAs<RValueReferenceType>()) {
6508 FnType = FnTypeRef->getPointeeType();
6509 isRValueReference = true;
6510 }
6511 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6512 FnType = FnTypePtr->getPointeeType();
6513 isPointer = true;
6514 }
6515 // Desugar down to a function type.
6516 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6517 // Reconstruct the pointer/reference as appropriate.
6518 if (isPointer) FnType = S.Context.getPointerType(FnType);
6519 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6520 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6521
6522 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6523 << FnType;
6524}
6525
6526void NoteBuiltinOperatorCandidate(Sema &S,
6527 const char *Opc,
6528 SourceLocation OpLoc,
6529 OverloadCandidate *Cand) {
6530 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6531 std::string TypeStr("operator");
6532 TypeStr += Opc;
6533 TypeStr += "(";
6534 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6535 if (Cand->Conversions.size() == 1) {
6536 TypeStr += ")";
6537 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6538 } else {
6539 TypeStr += ", ";
6540 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6541 TypeStr += ")";
6542 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6543 }
6544}
6545
6546void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6547 OverloadCandidate *Cand) {
6548 unsigned NoOperands = Cand->Conversions.size();
6549 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6550 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006551 if (ICS.isBad()) break; // all meaningless after first invalid
6552 if (!ICS.isAmbiguous()) continue;
6553
John McCall5c32be02010-08-24 20:38:10 +00006554 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006555 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006556 }
6557}
6558
John McCall3712d9e2010-01-15 23:32:50 +00006559SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6560 if (Cand->Function)
6561 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006562 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006563 return Cand->Surrogate->getLocation();
6564 return SourceLocation();
6565}
6566
John McCallad2587a2010-01-12 00:48:53 +00006567struct CompareOverloadCandidatesForDisplay {
6568 Sema &S;
6569 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006570
6571 bool operator()(const OverloadCandidate *L,
6572 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006573 // Fast-path this check.
6574 if (L == R) return false;
6575
John McCall12f97bc2010-01-08 04:41:39 +00006576 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006577 if (L->Viable) {
6578 if (!R->Viable) return true;
6579
6580 // TODO: introduce a tri-valued comparison for overload
6581 // candidates. Would be more worthwhile if we had a sort
6582 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006583 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6584 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006585 } else if (R->Viable)
6586 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006587
John McCall3712d9e2010-01-15 23:32:50 +00006588 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006589
John McCall3712d9e2010-01-15 23:32:50 +00006590 // Criteria by which we can sort non-viable candidates:
6591 if (!L->Viable) {
6592 // 1. Arity mismatches come after other candidates.
6593 if (L->FailureKind == ovl_fail_too_many_arguments ||
6594 L->FailureKind == ovl_fail_too_few_arguments)
6595 return false;
6596 if (R->FailureKind == ovl_fail_too_many_arguments ||
6597 R->FailureKind == ovl_fail_too_few_arguments)
6598 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006599
John McCallfe796dd2010-01-23 05:17:32 +00006600 // 2. Bad conversions come first and are ordered by the number
6601 // of bad conversions and quality of good conversions.
6602 if (L->FailureKind == ovl_fail_bad_conversion) {
6603 if (R->FailureKind != ovl_fail_bad_conversion)
6604 return true;
6605
6606 // If there's any ordering between the defined conversions...
6607 // FIXME: this might not be transitive.
6608 assert(L->Conversions.size() == R->Conversions.size());
6609
6610 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006611 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6612 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006613 switch (CompareImplicitConversionSequences(S,
6614 L->Conversions[I],
6615 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006616 case ImplicitConversionSequence::Better:
6617 leftBetter++;
6618 break;
6619
6620 case ImplicitConversionSequence::Worse:
6621 leftBetter--;
6622 break;
6623
6624 case ImplicitConversionSequence::Indistinguishable:
6625 break;
6626 }
6627 }
6628 if (leftBetter > 0) return true;
6629 if (leftBetter < 0) return false;
6630
6631 } else if (R->FailureKind == ovl_fail_bad_conversion)
6632 return false;
6633
John McCall3712d9e2010-01-15 23:32:50 +00006634 // TODO: others?
6635 }
6636
6637 // Sort everything else by location.
6638 SourceLocation LLoc = GetLocationForCandidate(L);
6639 SourceLocation RLoc = GetLocationForCandidate(R);
6640
6641 // Put candidates without locations (e.g. builtins) at the end.
6642 if (LLoc.isInvalid()) return false;
6643 if (RLoc.isInvalid()) return true;
6644
6645 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006646 }
6647};
6648
John McCallfe796dd2010-01-23 05:17:32 +00006649/// CompleteNonViableCandidate - Normally, overload resolution only
6650/// computes up to the first
6651void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6652 Expr **Args, unsigned NumArgs) {
6653 assert(!Cand->Viable);
6654
6655 // Don't do anything on failures other than bad conversion.
6656 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6657
6658 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006659 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006660 unsigned ConvCount = Cand->Conversions.size();
6661 while (true) {
6662 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6663 ConvIdx++;
6664 if (Cand->Conversions[ConvIdx - 1].isBad())
6665 break;
6666 }
6667
6668 if (ConvIdx == ConvCount)
6669 return;
6670
John McCall65eb8792010-02-25 01:37:24 +00006671 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6672 "remaining conversion is initialized?");
6673
Douglas Gregoradc7a702010-04-16 17:45:54 +00006674 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006675 // operation somehow.
6676 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006677
6678 const FunctionProtoType* Proto;
6679 unsigned ArgIdx = ConvIdx;
6680
6681 if (Cand->IsSurrogate) {
6682 QualType ConvType
6683 = Cand->Surrogate->getConversionType().getNonReferenceType();
6684 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6685 ConvType = ConvPtrType->getPointeeType();
6686 Proto = ConvType->getAs<FunctionProtoType>();
6687 ArgIdx--;
6688 } else if (Cand->Function) {
6689 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6690 if (isa<CXXMethodDecl>(Cand->Function) &&
6691 !isa<CXXConstructorDecl>(Cand->Function))
6692 ArgIdx--;
6693 } else {
6694 // Builtin binary operator with a bad first conversion.
6695 assert(ConvCount <= 3);
6696 for (; ConvIdx != ConvCount; ++ConvIdx)
6697 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006698 = TryCopyInitialization(S, Args[ConvIdx],
6699 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6700 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006701 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006702 return;
6703 }
6704
6705 // Fill in the rest of the conversions.
6706 unsigned NumArgsInProto = Proto->getNumArgs();
6707 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6708 if (ArgIdx < NumArgsInProto)
6709 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006710 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6711 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006712 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006713 else
6714 Cand->Conversions[ConvIdx].setEllipsis();
6715 }
6716}
6717
John McCalld3224162010-01-08 00:58:21 +00006718} // end anonymous namespace
6719
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006720/// PrintOverloadCandidates - When overload resolution fails, prints
6721/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006722/// set.
John McCall5c32be02010-08-24 20:38:10 +00006723void OverloadCandidateSet::NoteCandidates(Sema &S,
6724 OverloadCandidateDisplayKind OCD,
6725 Expr **Args, unsigned NumArgs,
6726 const char *Opc,
6727 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006728 // Sort the candidates by viability and position. Sorting directly would
6729 // be prohibitive, so we make a set of pointers and sort those.
6730 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006731 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6732 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006733 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006734 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006735 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006736 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006737 if (Cand->Function || Cand->IsSurrogate)
6738 Cands.push_back(Cand);
6739 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6740 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006741 }
6742 }
6743
John McCallad2587a2010-01-12 00:48:53 +00006744 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006745 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006746
John McCall0d1da222010-01-12 00:44:57 +00006747 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006748
John McCall12f97bc2010-01-08 04:41:39 +00006749 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006750 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006751 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006752 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6753 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006754
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006755 // Set an arbitrary limit on the number of candidate functions we'll spam
6756 // the user with. FIXME: This limit should depend on details of the
6757 // candidate list.
6758 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6759 break;
6760 }
6761 ++CandsShown;
6762
John McCalld3224162010-01-08 00:58:21 +00006763 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006764 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006765 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006766 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006767 else {
6768 assert(Cand->Viable &&
6769 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006770 // Generally we only see ambiguities including viable builtin
6771 // operators if overload resolution got screwed up by an
6772 // ambiguous user-defined conversion.
6773 //
6774 // FIXME: It's quite possible for different conversions to see
6775 // different ambiguities, though.
6776 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006777 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006778 ReportedAmbiguousConversions = true;
6779 }
John McCalld3224162010-01-08 00:58:21 +00006780
John McCall0d1da222010-01-12 00:44:57 +00006781 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006782 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006783 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006784 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006785
6786 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006787 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006788}
6789
John McCalla0296f72010-03-19 07:35:19 +00006790static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006791 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006792 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006793
John McCalla0296f72010-03-19 07:35:19 +00006794 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006795}
6796
Douglas Gregorcd695e52008-11-10 20:40:00 +00006797/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6798/// an overloaded function (C++ [over.over]), where @p From is an
6799/// expression with overloaded function type and @p ToType is the type
6800/// we're trying to resolve to. For example:
6801///
6802/// @code
6803/// int f(double);
6804/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006805///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006806/// int (*pfd)(double) = f; // selects f(double)
6807/// @endcode
6808///
6809/// This routine returns the resulting FunctionDecl if it could be
6810/// resolved, and NULL otherwise. When @p Complain is true, this
6811/// routine will emit diagnostics if there is an error.
6812FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006813Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006814 bool Complain,
6815 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006816 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006817 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006818 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006819 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006820 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006821 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006822 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006823 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006824 FunctionType = MemTypePtr->getPointeeType();
6825 IsMember = true;
6826 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006827
Douglas Gregorcd695e52008-11-10 20:40:00 +00006828 // C++ [over.over]p1:
6829 // [...] [Note: any redundant set of parentheses surrounding the
6830 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006831 // C++ [over.over]p1:
6832 // [...] The overloaded function name can be preceded by the &
6833 // operator.
John McCall7d460512010-08-24 23:26:21 +00006834 // However, remember whether the expression has member-pointer form:
6835 // C++ [expr.unary.op]p4:
6836 // A pointer to member is only formed when an explicit & is used
6837 // and its operand is a qualified-id not enclosed in
6838 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006839 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6840 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006841
Douglas Gregor064fdb22010-04-14 23:11:21 +00006842 // We expect a pointer or reference to function, or a function pointer.
6843 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6844 if (!FunctionType->isFunctionType()) {
6845 if (Complain)
6846 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6847 << OvlExpr->getName() << ToType;
6848
6849 return 0;
6850 }
6851
John McCall24d18942010-08-24 22:52:39 +00006852 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006853 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006854 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006855 if (!Complain) return 0;
6856
6857 // TODO: Should we condition this on whether any functions might
6858 // have matched, or is it more appropriate to do that in callers?
6859 // TODO: a fixit wouldn't hurt.
6860 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6861 << ToType << OvlExpr->getSourceRange();
6862 return 0;
6863 }
6864
6865 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6866 if (OvlExpr->hasExplicitTemplateArgs()) {
6867 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6868 ExplicitTemplateArgs = &ETABuffer;
6869 }
6870
Douglas Gregor064fdb22010-04-14 23:11:21 +00006871 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006872
Douglas Gregorcd695e52008-11-10 20:40:00 +00006873 // Look through all of the overloaded functions, searching for one
6874 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006875 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006876 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006877
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006878 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006879 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6880 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006881 // Look through any using declarations to find the underlying function.
6882 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6883
Douglas Gregorcd695e52008-11-10 20:40:00 +00006884 // C++ [over.over]p3:
6885 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006886 // targets of type "pointer-to-function" or "reference-to-function."
6887 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006888 // type "pointer-to-member-function."
6889 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006890
Mike Stump11289f42009-09-09 15:08:12 +00006891 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006892 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006893 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006894 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006895 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006896 // static when converting to member pointer.
6897 if (Method->isStatic() == IsMember)
6898 continue;
6899 } else if (IsMember)
6900 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006901
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006902 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006903 // If the name is a function template, template argument deduction is
6904 // done (14.8.2.2), and if the argument deduction succeeds, the
6905 // resulting template argument list is used to generate a single
6906 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006907 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006908 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006909 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006910 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006911 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006912 FunctionType, Specialization, Info)) {
6913 // FIXME: make a note of the failed deduction for diagnostics.
6914 (void)Result;
6915 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006916 // Template argument deduction ensures that we have an exact match.
6917 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006918 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006919 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006920 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006921 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006922 }
John McCalld14a8642009-11-21 08:51:07 +00006923
6924 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006925 }
Mike Stump11289f42009-09-09 15:08:12 +00006926
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006927 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006928 // Skip non-static functions when converting to pointer, and static
6929 // when converting to member pointer.
6930 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006931 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006932
6933 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006934 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006935 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006936 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006937 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006938
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006939 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006940 QualType ResultTy;
6941 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6942 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6943 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006944 Matches.push_back(std::make_pair(I.getPair(),
6945 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006946 FoundNonTemplateFunction = true;
6947 }
Mike Stump11289f42009-09-09 15:08:12 +00006948 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006949 }
6950
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006951 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006952 if (Matches.empty()) {
6953 if (Complain) {
6954 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6955 << OvlExpr->getName() << FunctionType;
6956 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6957 E = OvlExpr->decls_end();
6958 I != E; ++I)
6959 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6960 NoteOverloadCandidate(F);
6961 }
6962
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006963 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006964 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006965 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006966 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006967 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006968 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006969 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006970 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006971 return Result;
6972 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006973
6974 // C++ [over.over]p4:
6975 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006976 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006977 // [...] and any given function template specialization F1 is
6978 // eliminated if the set contains a second function template
6979 // specialization whose function template is more specialized
6980 // than the function template of F1 according to the partial
6981 // ordering rules of 14.5.5.2.
6982
6983 // The algorithm specified above is quadratic. We instead use a
6984 // two-pass algorithm (similar to the one used to identify the
6985 // best viable function in an overload set) that identifies the
6986 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006987
6988 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6989 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6990 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006991
6992 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006993 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00006994 TPOC_Other, 0, From->getLocStart(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006995 PDiag(),
6996 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006997 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006998 PDiag(diag::note_ovl_candidate)
6999 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00007000 if (Result == MatchesCopy.end())
7001 return 0;
7002
John McCall58cc69d2010-01-27 01:50:18 +00007003 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00007004 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007005 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00007006 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00007007 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007008 }
Mike Stump11289f42009-09-09 15:08:12 +00007009
Douglas Gregorfae1d712009-09-26 03:56:17 +00007010 // [...] any function template specializations in the set are
7011 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00007012 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00007013 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00007014 ++I;
7015 else {
John McCalla0296f72010-03-19 07:35:19 +00007016 Matches[I] = Matches[--N];
7017 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00007018 }
7019 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00007020
Mike Stump11289f42009-09-09 15:08:12 +00007021 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007022 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00007023 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00007024 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00007025 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007026 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00007027 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
7028 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007029 }
Mike Stump11289f42009-09-09 15:08:12 +00007030
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007031 // FIXME: We should probably return the same thing that BestViableFunction
7032 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00007033 if (Complain) {
7034 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7035 << Matches[0].second->getDeclName();
7036 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7037 NoteOverloadCandidate(Matches[I].second);
7038 }
7039
Douglas Gregorcd695e52008-11-10 20:40:00 +00007040 return 0;
7041}
7042
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007043/// \brief Given an expression that refers to an overloaded function, try to
7044/// resolve that overloaded function expression down to a single function.
7045///
7046/// This routine can only resolve template-ids that refer to a single function
7047/// template, where that template-id refers to a single template whose template
7048/// arguments are either provided by the template-id or have defaults,
7049/// as described in C++0x [temp.arg.explicit]p3.
7050FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
7051 // C++ [over.over]p1:
7052 // [...] [Note: any redundant set of parentheses surrounding the
7053 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007054 // C++ [over.over]p1:
7055 // [...] The overloaded function name can be preceded by the &
7056 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007057
7058 if (From->getType() != Context.OverloadTy)
7059 return 0;
7060
John McCall8d08b9b2010-08-27 09:08:28 +00007061 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007062
7063 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007064 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007065 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007066
7067 TemplateArgumentListInfo ExplicitTemplateArgs;
7068 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007069
7070 // Look through all of the overloaded functions, searching for one
7071 // whose type matches exactly.
7072 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007073 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7074 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007075 // C++0x [temp.arg.explicit]p3:
7076 // [...] In contexts where deduction is done and fails, or in contexts
7077 // where deduction is not done, if a template argument list is
7078 // specified and it, along with any default template arguments,
7079 // identifies a single function template specialization, then the
7080 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007081 FunctionTemplateDecl *FunctionTemplate
7082 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007083
7084 // C++ [over.over]p2:
7085 // If the name is a function template, template argument deduction is
7086 // done (14.8.2.2), and if the argument deduction succeeds, the
7087 // resulting template argument list is used to generate a single
7088 // function template specialization, which is added to the set of
7089 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007090 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007091 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007092 if (TemplateDeductionResult Result
7093 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7094 Specialization, Info)) {
7095 // FIXME: make a note of the failed deduction for diagnostics.
7096 (void)Result;
7097 continue;
7098 }
7099
7100 // Multiple matches; we can't resolve to a single declaration.
7101 if (Matched)
7102 return 0;
7103
7104 Matched = Specialization;
7105 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007106
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007107 return Matched;
7108}
7109
Douglas Gregorcabea402009-09-22 15:41:20 +00007110/// \brief Add a single candidate to the overload set.
7111static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007112 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00007113 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007114 Expr **Args, unsigned NumArgs,
7115 OverloadCandidateSet &CandidateSet,
7116 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007117 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007118 if (isa<UsingShadowDecl>(Callee))
7119 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7120
Douglas Gregorcabea402009-09-22 15:41:20 +00007121 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007122 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007123 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007124 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007125 return;
John McCalld14a8642009-11-21 08:51:07 +00007126 }
7127
7128 if (FunctionTemplateDecl *FuncTemplate
7129 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007130 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7131 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007132 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007133 return;
7134 }
7135
7136 assert(false && "unhandled case in overloaded call candidate");
7137
7138 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007139}
7140
7141/// \brief Add the overload candidates named by callee and/or found by argument
7142/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007143void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007144 Expr **Args, unsigned NumArgs,
7145 OverloadCandidateSet &CandidateSet,
7146 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007147
7148#ifndef NDEBUG
7149 // Verify that ArgumentDependentLookup is consistent with the rules
7150 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007151 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007152 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7153 // and let Y be the lookup set produced by argument dependent
7154 // lookup (defined as follows). If X contains
7155 //
7156 // -- a declaration of a class member, or
7157 //
7158 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007159 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007160 //
7161 // -- a declaration that is neither a function or a function
7162 // template
7163 //
7164 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007165
John McCall57500772009-12-16 12:17:52 +00007166 if (ULE->requiresADL()) {
7167 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7168 E = ULE->decls_end(); I != E; ++I) {
7169 assert(!(*I)->getDeclContext()->isRecord());
7170 assert(isa<UsingShadowDecl>(*I) ||
7171 !(*I)->getDeclContext()->isFunctionOrMethod());
7172 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007173 }
7174 }
7175#endif
7176
John McCall57500772009-12-16 12:17:52 +00007177 // It would be nice to avoid this copy.
7178 TemplateArgumentListInfo TABuffer;
7179 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7180 if (ULE->hasExplicitTemplateArgs()) {
7181 ULE->copyTemplateArgumentsInto(TABuffer);
7182 ExplicitTemplateArgs = &TABuffer;
7183 }
7184
7185 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7186 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007187 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007188 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007189 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007190
John McCall57500772009-12-16 12:17:52 +00007191 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007192 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7193 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007194 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007195 CandidateSet,
7196 PartialOverloading);
7197}
John McCalld681c392009-12-16 08:11:27 +00007198
7199/// Attempts to recover from a call where no functions were found.
7200///
7201/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007202static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007203BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007204 UnresolvedLookupExpr *ULE,
7205 SourceLocation LParenLoc,
7206 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007207 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007208
7209 CXXScopeSpec SS;
7210 if (ULE->getQualifier()) {
7211 SS.setScopeRep(ULE->getQualifier());
7212 SS.setRange(ULE->getQualifierRange());
7213 }
7214
John McCall57500772009-12-16 12:17:52 +00007215 TemplateArgumentListInfo TABuffer;
7216 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7217 if (ULE->hasExplicitTemplateArgs()) {
7218 ULE->copyTemplateArgumentsInto(TABuffer);
7219 ExplicitTemplateArgs = &TABuffer;
7220 }
7221
John McCalld681c392009-12-16 08:11:27 +00007222 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7223 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007224 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007225 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007226
John McCall57500772009-12-16 12:17:52 +00007227 assert(!R.empty() && "lookup results empty despite recovery");
7228
7229 // Build an implicit member call if appropriate. Just drop the
7230 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007231 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007232 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007233 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7234 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007235 else if (ExplicitTemplateArgs)
7236 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7237 else
7238 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7239
7240 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007241 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007242
7243 // This shouldn't cause an infinite loop because we're giving it
7244 // an expression with non-empty lookup results, which should never
7245 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007246 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007247 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007248}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007249
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007250/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007251/// (which eventually refers to the declaration Func) and the call
7252/// arguments Args/NumArgs, attempt to resolve the function call down
7253/// to a specific function. If overload resolution succeeds, returns
7254/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007255/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007256/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007257ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007258Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007259 SourceLocation LParenLoc,
7260 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007261 SourceLocation RParenLoc) {
7262#ifndef NDEBUG
7263 if (ULE->requiresADL()) {
7264 // To do ADL, we must have found an unqualified name.
7265 assert(!ULE->getQualifier() && "qualified name with ADL");
7266
7267 // We don't perform ADL for implicit declarations of builtins.
7268 // Verify that this was correctly set up.
7269 FunctionDecl *F;
7270 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7271 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7272 F->getBuiltinID() && F->isImplicit())
7273 assert(0 && "performing ADL for builtin");
7274
7275 // We don't perform ADL in C.
7276 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7277 }
7278#endif
7279
John McCallbc077cf2010-02-08 23:07:23 +00007280 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007281
John McCall57500772009-12-16 12:17:52 +00007282 // Add the functions denoted by the callee to the set of candidate
7283 // functions, including those from argument-dependent lookup.
7284 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007285
7286 // If we found nothing, try to recover.
7287 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7288 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007289 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007290 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007291 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007292
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007293 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007294 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007295 case OR_Success: {
7296 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007297 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007298 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7299 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007300 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007301 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7302 RParenLoc);
John McCall57500772009-12-16 12:17:52 +00007303 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007304
7305 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007306 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007307 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007308 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007309 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007310 break;
7311
7312 case OR_Ambiguous:
7313 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007314 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007315 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007316 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007317
7318 case OR_Deleted:
7319 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7320 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007321 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007322 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007323 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007324 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007325 }
7326
Douglas Gregorb412e172010-07-25 18:17:45 +00007327 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007328 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007329}
7330
John McCall4c4c1df2010-01-26 03:27:55 +00007331static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007332 return Functions.size() > 1 ||
7333 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7334}
7335
Douglas Gregor084d8552009-03-13 23:49:33 +00007336/// \brief Create a unary operation that may resolve to an overloaded
7337/// operator.
7338///
7339/// \param OpLoc The location of the operator itself (e.g., '*').
7340///
7341/// \param OpcIn The UnaryOperator::Opcode that describes this
7342/// operator.
7343///
7344/// \param Functions The set of non-member functions that will be
7345/// considered by overload resolution. The caller needs to build this
7346/// set based on the context using, e.g.,
7347/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7348/// set should not contain any member functions; those will be added
7349/// by CreateOverloadedUnaryOp().
7350///
7351/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007352ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007353Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7354 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007355 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007356 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007357
7358 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7359 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7360 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007361 // TODO: provide better source location info.
7362 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007363
John McCalle26a8722010-12-04 08:14:53 +00007364 if (Input->getObjectKind() == OK_ObjCProperty)
7365 ConvertPropertyForRValue(Input);
7366
Douglas Gregor084d8552009-03-13 23:49:33 +00007367 Expr *Args[2] = { Input, 0 };
7368 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007369
Douglas Gregor084d8552009-03-13 23:49:33 +00007370 // For post-increment and post-decrement, add the implicit '0' as
7371 // the second argument, so that we know this is a post-increment or
7372 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007373 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007374 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007375 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7376 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007377 NumArgs = 2;
7378 }
7379
7380 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007381 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007382 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007383 Opc,
7384 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007385 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007386 OpLoc));
7387
John McCall58cc69d2010-01-27 01:50:18 +00007388 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007389 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007390 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007391 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007392 /*ADL*/ true, IsOverloaded(Fns),
7393 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007394 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7395 &Args[0], NumArgs,
7396 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007397 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007398 OpLoc));
7399 }
7400
7401 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007402 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007403
7404 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007405 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007406
7407 // Add operator candidates that are member functions.
7408 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7409
John McCall4c4c1df2010-01-26 03:27:55 +00007410 // Add candidates from ADL.
7411 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007412 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007413 /*ExplicitTemplateArgs*/ 0,
7414 CandidateSet);
7415
Douglas Gregor084d8552009-03-13 23:49:33 +00007416 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007417 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007418
7419 // Perform overload resolution.
7420 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007421 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007422 case OR_Success: {
7423 // We found a built-in operator or an overloaded operator.
7424 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007425
Douglas Gregor084d8552009-03-13 23:49:33 +00007426 if (FnDecl) {
7427 // We matched an overloaded operator. Build a call to that
7428 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007429
Douglas Gregor084d8552009-03-13 23:49:33 +00007430 // Convert the arguments.
7431 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007432 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007433
John McCall16df1e52010-03-30 21:47:33 +00007434 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7435 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007436 return ExprError();
7437 } else {
7438 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007439 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007440 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007441 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007442 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007443 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007444 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007445 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007446 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007447 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007448 }
7449
John McCall4fa0d5f2010-05-06 18:15:07 +00007450 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7451
John McCall7decc9e2010-11-18 06:31:45 +00007452 // Determine the result type.
7453 QualType ResultTy = FnDecl->getResultType();
7454 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7455 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007456
Douglas Gregor084d8552009-03-13 23:49:33 +00007457 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007458 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007459
Eli Friedman030eee42009-11-18 03:58:17 +00007460 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007461 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007462 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007463 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007464
John McCallb268a282010-08-23 23:25:46 +00007465 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007466 FnDecl))
7467 return ExprError();
7468
John McCallb268a282010-08-23 23:25:46 +00007469 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007470 } else {
7471 // We matched a built-in operator. Convert the arguments, then
7472 // break out so that we will build the appropriate built-in
7473 // operator node.
7474 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007475 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007476 return ExprError();
7477
7478 break;
7479 }
7480 }
7481
7482 case OR_No_Viable_Function:
7483 // No viable function; fall through to handling this as a
7484 // built-in operator, which will produce an error message for us.
7485 break;
7486
7487 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007488 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007489 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007490 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007491 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007492 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7493 Args, NumArgs,
7494 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007495 return ExprError();
7496
7497 case OR_Deleted:
7498 Diag(OpLoc, diag::err_ovl_deleted_oper)
7499 << Best->Function->isDeleted()
7500 << UnaryOperator::getOpcodeStr(Opc)
7501 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007502 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007503 return ExprError();
7504 }
7505
7506 // Either we found no viable overloaded operator or we matched a
7507 // built-in operator. In either case, fall through to trying to
7508 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007509 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007510}
7511
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007512/// \brief Create a binary operation that may resolve to an overloaded
7513/// operator.
7514///
7515/// \param OpLoc The location of the operator itself (e.g., '+').
7516///
7517/// \param OpcIn The BinaryOperator::Opcode that describes this
7518/// operator.
7519///
7520/// \param Functions The set of non-member functions that will be
7521/// considered by overload resolution. The caller needs to build this
7522/// set based on the context using, e.g.,
7523/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7524/// set should not contain any member functions; those will be added
7525/// by CreateOverloadedBinOp().
7526///
7527/// \param LHS Left-hand argument.
7528/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007529ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007530Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007531 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007532 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007533 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007534 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007535 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007536
7537 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7538 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7539 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7540
7541 // If either side is type-dependent, create an appropriate dependent
7542 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007543 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007544 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007545 // If there are no functions to store, just build a dependent
7546 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007547 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007548 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007549 Context.DependentTy,
7550 VK_RValue, OK_Ordinary,
7551 OpLoc));
Douglas Gregor5287f092009-11-05 00:51:44 +00007552
7553 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7554 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007555 VK_LValue,
7556 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007557 Context.DependentTy,
7558 Context.DependentTy,
7559 OpLoc));
7560 }
John McCall4c4c1df2010-01-26 03:27:55 +00007561
7562 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007563 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007564 // TODO: provide better source location info in DNLoc component.
7565 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007566 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007567 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
7568 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007569 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007570 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007571 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007572 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007573 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007574 OpLoc));
7575 }
7576
John McCalle26a8722010-12-04 08:14:53 +00007577 // Always do property rvalue conversions on the RHS.
7578 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7579 ConvertPropertyForRValue(Args[1]);
7580
7581 // The LHS is more complicated.
7582 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7583
7584 // There's a tension for assignment operators between primitive
7585 // property assignment and the overloaded operators.
7586 if (BinaryOperator::isAssignmentOp(Opc)) {
7587 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7588
7589 // Is the property "logically" settable?
7590 bool Settable = (PRE->isExplicitProperty() ||
7591 PRE->getImplicitPropertySetter());
7592
7593 // To avoid gratuitously inventing semantics, use the primitive
7594 // unless it isn't. Thoughts in case we ever really care:
7595 // - If the property isn't logically settable, we have to
7596 // load and hope.
7597 // - If the property is settable and this is simple assignment,
7598 // we really should use the primitive.
7599 // - If the property is settable, then we could try overloading
7600 // on a generic lvalue of the appropriate type; if it works
7601 // out to a builtin candidate, we would do that same operation
7602 // on the property, and otherwise just error.
7603 if (Settable)
7604 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7605 }
7606
7607 ConvertPropertyForRValue(Args[0]);
7608 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007609
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007610 // If this is the assignment operator, we only perform overload resolution
7611 // if the left-hand side is a class or enumeration type. This is actually
7612 // a hack. The standard requires that we do overload resolution between the
7613 // various built-in candidates, but as DR507 points out, this can lead to
7614 // problems. So we do it this way, which pretty much follows what GCC does.
7615 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007616 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007617 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007618
John McCalle26a8722010-12-04 08:14:53 +00007619 // If this is the .* operator, which is not overloadable, just
7620 // create a built-in binary operator.
7621 if (Opc == BO_PtrMemD)
7622 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7623
Douglas Gregor084d8552009-03-13 23:49:33 +00007624 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007625 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007626
7627 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007628 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007629
7630 // Add operator candidates that are member functions.
7631 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7632
John McCall4c4c1df2010-01-26 03:27:55 +00007633 // Add candidates from ADL.
7634 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7635 Args, 2,
7636 /*ExplicitTemplateArgs*/ 0,
7637 CandidateSet);
7638
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007639 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007640 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007641
7642 // Perform overload resolution.
7643 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007644 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007645 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007646 // We found a built-in operator or an overloaded operator.
7647 FunctionDecl *FnDecl = Best->Function;
7648
7649 if (FnDecl) {
7650 // We matched an overloaded operator. Build a call to that
7651 // operator.
7652
7653 // Convert the arguments.
7654 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007655 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007656 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007657
Chandler Carruth8e543b32010-12-12 08:17:55 +00007658 ExprResult Arg1 =
7659 PerformCopyInitialization(
7660 InitializedEntity::InitializeParameter(Context,
7661 FnDecl->getParamDecl(0)),
7662 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007663 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007664 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007665
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007666 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007667 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007668 return ExprError();
7669
7670 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007671 } else {
7672 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00007673 ExprResult Arg0 = PerformCopyInitialization(
7674 InitializedEntity::InitializeParameter(Context,
7675 FnDecl->getParamDecl(0)),
7676 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007677 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007678 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007679
Chandler Carruth8e543b32010-12-12 08:17:55 +00007680 ExprResult Arg1 =
7681 PerformCopyInitialization(
7682 InitializedEntity::InitializeParameter(Context,
7683 FnDecl->getParamDecl(1)),
7684 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007685 if (Arg1.isInvalid())
7686 return ExprError();
7687 Args[0] = LHS = Arg0.takeAs<Expr>();
7688 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007689 }
7690
John McCall4fa0d5f2010-05-06 18:15:07 +00007691 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7692
John McCall7decc9e2010-11-18 06:31:45 +00007693 // Determine the result type.
7694 QualType ResultTy = FnDecl->getResultType();
7695 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7696 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007697
7698 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007699 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007700
John McCallb268a282010-08-23 23:25:46 +00007701 CXXOperatorCallExpr *TheCall =
7702 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007703 Args, 2, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007704
John McCallb268a282010-08-23 23:25:46 +00007705 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007706 FnDecl))
7707 return ExprError();
7708
John McCallb268a282010-08-23 23:25:46 +00007709 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007710 } else {
7711 // We matched a built-in operator. Convert the arguments, then
7712 // break out so that we will build the appropriate built-in
7713 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007714 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007715 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007716 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007717 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007718 return ExprError();
7719
7720 break;
7721 }
7722 }
7723
Douglas Gregor66950a32009-09-30 21:46:01 +00007724 case OR_No_Viable_Function: {
7725 // C++ [over.match.oper]p9:
7726 // If the operator is the operator , [...] and there are no
7727 // viable functions, then the operator is assumed to be the
7728 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007729 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007730 break;
7731
Chandler Carruth8e543b32010-12-12 08:17:55 +00007732 // For class as left operand for assignment or compound assigment
7733 // operator do not fall through to handling in built-in, but report that
7734 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007735 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007736 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007737 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007738 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7739 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007740 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007741 } else {
7742 // No viable function; try to create a built-in operation, which will
7743 // produce an error. Then, show the non-viable candidates.
7744 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007745 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007746 assert(Result.isInvalid() &&
7747 "C++ binary operator overloading is missing candidates!");
7748 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007749 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7750 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007751 return move(Result);
7752 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007753
7754 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007755 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007756 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007757 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007758 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007759 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7760 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007761 return ExprError();
7762
7763 case OR_Deleted:
7764 Diag(OpLoc, diag::err_ovl_deleted_oper)
7765 << Best->Function->isDeleted()
7766 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007767 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007768 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007769 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007770 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007771
Douglas Gregor66950a32009-09-30 21:46:01 +00007772 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007773 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007774}
7775
John McCalldadc5752010-08-24 06:29:42 +00007776ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007777Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7778 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007779 Expr *Base, Expr *Idx) {
7780 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007781 DeclarationName OpName =
7782 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7783
7784 // If either side is type-dependent, create an appropriate dependent
7785 // expression.
7786 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7787
John McCall58cc69d2010-01-27 01:50:18 +00007788 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007789 // CHECKME: no 'operator' keyword?
7790 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7791 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007792 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007793 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007794 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007795 /*ADL*/ true, /*Overloaded*/ false,
7796 UnresolvedSetIterator(),
7797 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007798 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007799
Sebastian Redladba46e2009-10-29 20:17:01 +00007800 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7801 Args, 2,
7802 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007803 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007804 RLoc));
7805 }
7806
John McCalle26a8722010-12-04 08:14:53 +00007807 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7808 ConvertPropertyForRValue(Args[0]);
7809 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7810 ConvertPropertyForRValue(Args[1]);
7811
Sebastian Redladba46e2009-10-29 20:17:01 +00007812 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007813 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007814
7815 // Subscript can only be overloaded as a member function.
7816
7817 // Add operator candidates that are member functions.
7818 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7819
7820 // Add builtin operator candidates.
7821 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7822
7823 // Perform overload resolution.
7824 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007825 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007826 case OR_Success: {
7827 // We found a built-in operator or an overloaded operator.
7828 FunctionDecl *FnDecl = Best->Function;
7829
7830 if (FnDecl) {
7831 // We matched an overloaded operator. Build a call to that
7832 // operator.
7833
John McCalla0296f72010-03-19 07:35:19 +00007834 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007835 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007836
Sebastian Redladba46e2009-10-29 20:17:01 +00007837 // Convert the arguments.
7838 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007839 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007840 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007841 return ExprError();
7842
Anders Carlssona68e51e2010-01-29 18:37:50 +00007843 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007844 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007845 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007846 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007847 FnDecl->getParamDecl(0)),
7848 SourceLocation(),
7849 Owned(Args[1]));
7850 if (InputInit.isInvalid())
7851 return ExprError();
7852
7853 Args[1] = InputInit.takeAs<Expr>();
7854
Sebastian Redladba46e2009-10-29 20:17:01 +00007855 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007856 QualType ResultTy = FnDecl->getResultType();
7857 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7858 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007859
7860 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007861 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007862
John McCallb268a282010-08-23 23:25:46 +00007863 CXXOperatorCallExpr *TheCall =
7864 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7865 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00007866 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007867
John McCallb268a282010-08-23 23:25:46 +00007868 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007869 FnDecl))
7870 return ExprError();
7871
John McCallb268a282010-08-23 23:25:46 +00007872 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007873 } else {
7874 // We matched a built-in operator. Convert the arguments, then
7875 // break out so that we will build the appropriate built-in
7876 // operator node.
7877 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007878 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007879 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007880 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007881 return ExprError();
7882
7883 break;
7884 }
7885 }
7886
7887 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007888 if (CandidateSet.empty())
7889 Diag(LLoc, diag::err_ovl_no_oper)
7890 << Args[0]->getType() << /*subscript*/ 0
7891 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7892 else
7893 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7894 << Args[0]->getType()
7895 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007896 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7897 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007898 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007899 }
7900
7901 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007902 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7903 << "[]"
7904 << Args[0]->getType() << Args[1]->getType()
7905 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007906 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7907 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007908 return ExprError();
7909
7910 case OR_Deleted:
7911 Diag(LLoc, diag::err_ovl_deleted_oper)
7912 << Best->Function->isDeleted() << "[]"
7913 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007914 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7915 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007916 return ExprError();
7917 }
7918
7919 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007920 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007921}
7922
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007923/// BuildCallToMemberFunction - Build a call to a member
7924/// function. MemExpr is the expression that refers to the member
7925/// function (and includes the object parameter), Args/NumArgs are the
7926/// arguments to the function call (not including the object
7927/// parameter). The caller needs to validate that the member
7928/// expression refers to a member function or an overloaded member
7929/// function.
John McCalldadc5752010-08-24 06:29:42 +00007930ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007931Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7932 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007933 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007934 // Dig out the member expression. This holds both the object
7935 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007936 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7937
John McCall10eae182009-11-30 22:42:35 +00007938 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007939 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007940 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007941 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007942 if (isa<MemberExpr>(NakedMemExpr)) {
7943 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007944 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007945 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007946 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007947 } else {
7948 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007949 Qualifier = UnresExpr->getQualifier();
7950
John McCall6e9f8f62009-12-03 04:06:58 +00007951 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007952
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007953 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007954 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007955
John McCall2d74de92009-12-01 22:10:20 +00007956 // FIXME: avoid copy.
7957 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7958 if (UnresExpr->hasExplicitTemplateArgs()) {
7959 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7960 TemplateArgs = &TemplateArgsBuffer;
7961 }
7962
John McCall10eae182009-11-30 22:42:35 +00007963 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7964 E = UnresExpr->decls_end(); I != E; ++I) {
7965
John McCall6e9f8f62009-12-03 04:06:58 +00007966 NamedDecl *Func = *I;
7967 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7968 if (isa<UsingShadowDecl>(Func))
7969 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7970
Francois Pichet64225792011-01-18 05:04:39 +00007971 // Microsoft supports direct constructor calls.
7972 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
7973 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
7974 CandidateSet);
7975 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007976 // If explicit template arguments were provided, we can't call a
7977 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007978 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007979 continue;
7980
John McCalla0296f72010-03-19 07:35:19 +00007981 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007982 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007983 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007984 } else {
John McCall10eae182009-11-30 22:42:35 +00007985 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007986 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007987 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007988 CandidateSet,
7989 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007990 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007991 }
Mike Stump11289f42009-09-09 15:08:12 +00007992
John McCall10eae182009-11-30 22:42:35 +00007993 DeclarationName DeclName = UnresExpr->getMemberName();
7994
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007995 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007996 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00007997 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007998 case OR_Success:
7999 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008000 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008001 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008002 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008003 break;
8004
8005 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008006 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008007 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008008 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008009 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008010 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008011 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008012
8013 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008014 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008015 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008016 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008017 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008018 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008019
8020 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008021 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008022 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00008023 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008024 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008025 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008026 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008027 }
8028
John McCall16df1e52010-03-30 21:47:33 +00008029 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008030
John McCall2d74de92009-12-01 22:10:20 +00008031 // If overload resolution picked a static member, build a
8032 // non-member call based on that function.
8033 if (Method->isStatic()) {
8034 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8035 Args, NumArgs, RParenLoc);
8036 }
8037
John McCall10eae182009-11-30 22:42:35 +00008038 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008039 }
8040
John McCall7decc9e2010-11-18 06:31:45 +00008041 QualType ResultType = Method->getResultType();
8042 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8043 ResultType = ResultType.getNonLValueExprType(Context);
8044
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008045 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00008046 CXXMemberCallExpr *TheCall =
8047 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008048 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008049
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008050 // Check for a valid return type.
8051 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008052 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008053 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008054
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008055 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008056 // We only need to do this if there was actually an overload; otherwise
8057 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008058 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008059 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008060 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8061 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008062 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008063 MemExpr->setBase(ObjectArg);
8064
8065 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008066 const FunctionProtoType *Proto =
8067 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008068 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008069 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008070 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008071
John McCallb268a282010-08-23 23:25:46 +00008072 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008073 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008074
John McCallb268a282010-08-23 23:25:46 +00008075 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008076}
8077
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008078/// BuildCallToObjectOfClassType - Build a call to an object of class
8079/// type (C++ [over.call.object]), which can end up invoking an
8080/// overloaded function call operator (@c operator()) or performing a
8081/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008082ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008083Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008084 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008085 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008086 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008087 if (Object->getObjectKind() == OK_ObjCProperty)
8088 ConvertPropertyForRValue(Object);
8089
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008090 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008091 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008092
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008093 // C++ [over.call.object]p1:
8094 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008095 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008096 // candidate functions includes at least the function call
8097 // operators of T. The function call operators of T are obtained by
8098 // ordinary lookup of the name operator() in the context of
8099 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008100 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008101 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008102
8103 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008104 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008105 << Object->getSourceRange()))
8106 return true;
8107
John McCall27b18f82009-11-17 02:14:36 +00008108 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8109 LookupQualifiedName(R, Record->getDecl());
8110 R.suppressDiagnostics();
8111
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008112 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008113 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008114 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00008115 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008116 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008117 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008118
Douglas Gregorab7897a2008-11-19 22:57:39 +00008119 // C++ [over.call.object]p2:
8120 // In addition, for each conversion function declared in T of the
8121 // form
8122 //
8123 // operator conversion-type-id () cv-qualifier;
8124 //
8125 // where cv-qualifier is the same cv-qualification as, or a
8126 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008127 // denotes the type "pointer to function of (P1,...,Pn) returning
8128 // R", or the type "reference to pointer to function of
8129 // (P1,...,Pn) returning R", or the type "reference to function
8130 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008131 // is also considered as a candidate function. Similarly,
8132 // surrogate call functions are added to the set of candidate
8133 // functions for each conversion function declared in an
8134 // accessible base class provided the function is not hidden
8135 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008136 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008137 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008138 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008139 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008140 NamedDecl *D = *I;
8141 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8142 if (isa<UsingShadowDecl>(D))
8143 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8144
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008145 // Skip over templated conversion functions; they aren't
8146 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008147 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008148 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008149
John McCall6e9f8f62009-12-03 04:06:58 +00008150 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008151
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008152 // Strip the reference type (if any) and then the pointer type (if
8153 // any) to get down to what might be a function type.
8154 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8155 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8156 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008157
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008158 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008159 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00008160 Object->getType(), Args, NumArgs,
8161 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008162 }
Mike Stump11289f42009-09-09 15:08:12 +00008163
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008164 // Perform overload resolution.
8165 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008166 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8167 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008168 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008169 // Overload resolution succeeded; we'll build the appropriate call
8170 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008171 break;
8172
8173 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008174 if (CandidateSet.empty())
8175 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8176 << Object->getType() << /*call*/ 1
8177 << Object->getSourceRange();
8178 else
8179 Diag(Object->getSourceRange().getBegin(),
8180 diag::err_ovl_no_viable_object_call)
8181 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008182 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008183 break;
8184
8185 case OR_Ambiguous:
8186 Diag(Object->getSourceRange().getBegin(),
8187 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008188 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008189 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008190 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008191
8192 case OR_Deleted:
8193 Diag(Object->getSourceRange().getBegin(),
8194 diag::err_ovl_deleted_object_call)
8195 << Best->Function->isDeleted()
8196 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008197 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008198 break;
Mike Stump11289f42009-09-09 15:08:12 +00008199 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008200
Douglas Gregorb412e172010-07-25 18:17:45 +00008201 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008202 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008203
Douglas Gregorab7897a2008-11-19 22:57:39 +00008204 if (Best->Function == 0) {
8205 // Since there is no function declaration, this is one of the
8206 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008207 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008208 = cast<CXXConversionDecl>(
8209 Best->Conversions[0].UserDefined.ConversionFunction);
8210
John McCalla0296f72010-03-19 07:35:19 +00008211 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008212 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008213
Douglas Gregorab7897a2008-11-19 22:57:39 +00008214 // We selected one of the surrogate functions that converts the
8215 // object parameter to a function pointer. Perform the conversion
8216 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008217
8218 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008219 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008220 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8221 if (Call.isInvalid())
8222 return ExprError();
8223
8224 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008225 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008226 }
8227
John McCalla0296f72010-03-19 07:35:19 +00008228 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008229 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008230
Douglas Gregorab7897a2008-11-19 22:57:39 +00008231 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8232 // that calls this method, using Object for the implicit object
8233 // parameter and passing along the remaining arguments.
8234 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008235 const FunctionProtoType *Proto =
8236 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008237
8238 unsigned NumArgsInProto = Proto->getNumArgs();
8239 unsigned NumArgsToCheck = NumArgs;
8240
8241 // Build the full argument list for the method call (the
8242 // implicit object parameter is placed at the beginning of the
8243 // list).
8244 Expr **MethodArgs;
8245 if (NumArgs < NumArgsInProto) {
8246 NumArgsToCheck = NumArgsInProto;
8247 MethodArgs = new Expr*[NumArgsInProto + 1];
8248 } else {
8249 MethodArgs = new Expr*[NumArgs + 1];
8250 }
8251 MethodArgs[0] = Object;
8252 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8253 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008254
John McCall7decc9e2010-11-18 06:31:45 +00008255 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008256
8257 // Once we've built TheCall, all of the expressions are properly
8258 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008259 QualType ResultTy = Method->getResultType();
8260 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8261 ResultTy = ResultTy.getNonLValueExprType(Context);
8262
John McCallb268a282010-08-23 23:25:46 +00008263 CXXOperatorCallExpr *TheCall =
8264 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8265 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008266 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008267 delete [] MethodArgs;
8268
John McCallb268a282010-08-23 23:25:46 +00008269 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008270 Method))
8271 return true;
8272
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008273 // We may have default arguments. If so, we need to allocate more
8274 // slots in the call for them.
8275 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008276 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008277 else if (NumArgs > NumArgsInProto)
8278 NumArgsToCheck = NumArgsInProto;
8279
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008280 bool IsError = false;
8281
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008282 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008283 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008284 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008285 TheCall->setArg(0, Object);
8286
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008287
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008288 // Check the argument types.
8289 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008290 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008291 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008292 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008293
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008294 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008295
John McCalldadc5752010-08-24 06:29:42 +00008296 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008297 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008298 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008299 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008300 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008301
8302 IsError |= InputInit.isInvalid();
8303 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008304 } else {
John McCalldadc5752010-08-24 06:29:42 +00008305 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008306 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8307 if (DefArg.isInvalid()) {
8308 IsError = true;
8309 break;
8310 }
8311
8312 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008313 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008314
8315 TheCall->setArg(i + 1, Arg);
8316 }
8317
8318 // If this is a variadic call, handle args passed through "...".
8319 if (Proto->isVariadic()) {
8320 // Promote the arguments (C99 6.5.2.2p7).
8321 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8322 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008323 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008324 TheCall->setArg(i + 1, Arg);
8325 }
8326 }
8327
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008328 if (IsError) return true;
8329
John McCallb268a282010-08-23 23:25:46 +00008330 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008331 return true;
8332
John McCalle172be52010-08-24 06:09:16 +00008333 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008334}
8335
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008336/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008337/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008338/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008339ExprResult
John McCallb268a282010-08-23 23:25:46 +00008340Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008341 assert(Base->getType()->isRecordType() &&
8342 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008343
John McCalle26a8722010-12-04 08:14:53 +00008344 if (Base->getObjectKind() == OK_ObjCProperty)
8345 ConvertPropertyForRValue(Base);
8346
John McCallbc077cf2010-02-08 23:07:23 +00008347 SourceLocation Loc = Base->getExprLoc();
8348
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008349 // C++ [over.ref]p1:
8350 //
8351 // [...] An expression x->m is interpreted as (x.operator->())->m
8352 // for a class object x of type T if T::operator->() exists and if
8353 // the operator is selected as the best match function by the
8354 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008355 DeclarationName OpName =
8356 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008357 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008358 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008359
John McCallbc077cf2010-02-08 23:07:23 +00008360 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008361 PDiag(diag::err_typecheck_incomplete_tag)
8362 << Base->getSourceRange()))
8363 return ExprError();
8364
John McCall27b18f82009-11-17 02:14:36 +00008365 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8366 LookupQualifiedName(R, BaseRecord->getDecl());
8367 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008368
8369 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008370 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008371 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008372 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008373 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008374
8375 // Perform overload resolution.
8376 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008377 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008378 case OR_Success:
8379 // Overload resolution succeeded; we'll build the call below.
8380 break;
8381
8382 case OR_No_Viable_Function:
8383 if (CandidateSet.empty())
8384 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008385 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008386 else
8387 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008388 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008389 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008390 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008391
8392 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008393 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8394 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008395 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008396 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008397
8398 case OR_Deleted:
8399 Diag(OpLoc, diag::err_ovl_deleted_oper)
8400 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008401 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008402 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008403 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008404 }
8405
John McCalla0296f72010-03-19 07:35:19 +00008406 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008407 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008408
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008409 // Convert the object parameter.
8410 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008411 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8412 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008413 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008414
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008415 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008416 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008417
John McCall7decc9e2010-11-18 06:31:45 +00008418 QualType ResultTy = Method->getResultType();
8419 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8420 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008421 CXXOperatorCallExpr *TheCall =
8422 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008423 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008424
John McCallb268a282010-08-23 23:25:46 +00008425 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008426 Method))
8427 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008428 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008429}
8430
Douglas Gregorcd695e52008-11-10 20:40:00 +00008431/// FixOverloadedFunctionReference - E is an expression that refers to
8432/// a C++ overloaded function (possibly with some parentheses and
8433/// perhaps a '&' around it). We have resolved the overloaded function
8434/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008435/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008436Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008437 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008438 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008439 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8440 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008441 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008442 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008443
8444 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8445 }
8446
8447 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008448 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8449 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008450 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008451 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008452 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008453 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008454 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008455 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008456
John McCallcf142162010-08-07 06:22:56 +00008457 return ImplicitCastExpr::Create(Context, ICE->getType(),
8458 ICE->getCastKind(),
8459 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008460 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008461 }
8462
8463 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008464 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008465 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008466 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8467 if (Method->isStatic()) {
8468 // Do nothing: static member functions aren't any different
8469 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008470 } else {
John McCalle66edc12009-11-24 19:00:30 +00008471 // Fix the sub expression, which really has to be an
8472 // UnresolvedLookupExpr holding an overloaded member function
8473 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008474 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8475 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008476 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008477 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008478
John McCalld14a8642009-11-21 08:51:07 +00008479 assert(isa<DeclRefExpr>(SubExpr)
8480 && "fixed to something other than a decl ref");
8481 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8482 && "fixed to a member ref with no nested name qualifier");
8483
8484 // We have taken the address of a pointer to member
8485 // function. Perform the computation here so that we get the
8486 // appropriate pointer to member type.
8487 QualType ClassType
8488 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8489 QualType MemPtrType
8490 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8491
John McCall7decc9e2010-11-18 06:31:45 +00008492 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8493 VK_RValue, OK_Ordinary,
8494 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008495 }
8496 }
John McCall16df1e52010-03-30 21:47:33 +00008497 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8498 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008499 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008500 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008501
John McCalle3027922010-08-25 11:45:40 +00008502 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008503 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008504 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008505 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008506 }
John McCalld14a8642009-11-21 08:51:07 +00008507
8508 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008509 // FIXME: avoid copy.
8510 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008511 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008512 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8513 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008514 }
8515
John McCalld14a8642009-11-21 08:51:07 +00008516 return DeclRefExpr::Create(Context,
8517 ULE->getQualifier(),
8518 ULE->getQualifierRange(),
8519 Fn,
8520 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008521 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008522 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008523 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008524 }
8525
John McCall10eae182009-11-30 22:42:35 +00008526 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008527 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008528 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8529 if (MemExpr->hasExplicitTemplateArgs()) {
8530 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8531 TemplateArgs = &TemplateArgsBuffer;
8532 }
John McCall6b51f282009-11-23 01:53:49 +00008533
John McCall2d74de92009-12-01 22:10:20 +00008534 Expr *Base;
8535
John McCall7decc9e2010-11-18 06:31:45 +00008536 // If we're filling in a static method where we used to have an
8537 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008538 if (MemExpr->isImplicitAccess()) {
8539 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8540 return DeclRefExpr::Create(Context,
8541 MemExpr->getQualifier(),
8542 MemExpr->getQualifierRange(),
8543 Fn,
8544 MemExpr->getMemberLoc(),
8545 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008546 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008547 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008548 } else {
8549 SourceLocation Loc = MemExpr->getMemberLoc();
8550 if (MemExpr->getQualifier())
8551 Loc = MemExpr->getQualifierRange().getBegin();
8552 Base = new (Context) CXXThisExpr(Loc,
8553 MemExpr->getBaseType(),
8554 /*isImplicit=*/true);
8555 }
John McCall2d74de92009-12-01 22:10:20 +00008556 } else
John McCallc3007a22010-10-26 07:05:15 +00008557 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008558
8559 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008560 MemExpr->isArrow(),
8561 MemExpr->getQualifier(),
8562 MemExpr->getQualifierRange(),
8563 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008564 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008565 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008566 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008567 Fn->getType(),
8568 cast<CXXMethodDecl>(Fn)->isStatic()
8569 ? VK_LValue : VK_RValue,
8570 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008571 }
8572
John McCallc3007a22010-10-26 07:05:15 +00008573 llvm_unreachable("Invalid reference to overloaded function");
8574 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008575}
8576
John McCalldadc5752010-08-24 06:29:42 +00008577ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8578 DeclAccessPair Found,
8579 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008580 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008581}
8582
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008583} // end namespace clang